• Android 利用Gson生成或解析json


    目前手机端和服务端数据交流格式一般是json,而谷歌提供了Gson来解析json。下载Gson:https://code.google.com/p/google-gson/

    下载的放在lib并导入,若出现错误:java.lang.NoClassDefFoundError: com.google.gson.Gson

    是因为没有导入android-support-v4.jar,导入即可。

    一、单个对象生成json

    生成以下类,该怎么生成呢?

    {
        "createDate": "2015-02-01 10:39:50",
        "id": "1",
        "name": "传说之美",
        "password": "123456"
    }

    先定义一个account类,属性有id、name、password、createDate。

    public class Account {
        private String id;
        private String password;
        private String name;
        private String createDate;
        public Account() {
            super();
        }
        public Account(String id, String password, String name, String createDate) {
            super();
            this.id = id;
            this.password = password;
            this.name = name;
            this.createDate = createDate;
        }
        public String getId() {
            return id;
        }
        public void setId(String id) {
            this.id = id;
        }
        public String getPassword() {
            return password;
        }
        public void setPassword(String password) {
            this.password = password;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getCreateDate() {
            return createDate;
        }
        public void setCreateDate(String createDate) {
            this.createDate = createDate;
        }
        @Override
        public String toString() {
            return "Account [id=" + id + ", password=" + password + ", name=" + name + ", createDate=" + createDate + "]
    
    ";
        }
    }

    定义好这个类,就可以利用Gson生成json字符串了。

    // 生成account对象
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    Account account = new Account("1", "123456", "传说之美", sdf.format(new Date()));
     
    // 利用gson对象生成json字符串
    Gson gson = new Gson();
    String jsonString = gson.toJson(account);
    Log.i("", jsonString);

    输入的log如下

     二、解析json字符串单个对象

     在上面已生成了jsonString,那如何将其解析为单个对象,很简单。

    // 利用gson解析json字符串为单个对象
    Account account1 = gson.fromJson(jsonString, Account.class);
    Log.i("", account1.toString());

    三、生成单个对象的json数组

    什么事json数组,类似下面的

    [
        {
            "id": "2",
            "createDate": "2015-02-01 11:21:27",
            "password": "123456",
            "name": "传说"
        },
        {
            "id": "2",
            "createDate": "2015-02-01 11:21:27",
            "password": "123456",
            "name": "之美"
        }
    ]
    

    生成json数组代码如下

    Account account2 = new Account("2", "123456", "传说", sdf.format(new Date()));
    Account account3 = new Account("2", "123456", "之美", sdf.format(new Date()));
    List<Account> accountList = new ArrayList<Account>();
    accountList.add(account2);
    accountList.add(account3);
     
     
    JSONArray accountArray = new JSONArray();
    for (int i = 0; i < accountList.size(); i++) {
        String accountStr = gson.toJson(accountList.get(i));
        JSONObject accountObject;
        try {
            accountObject = new JSONObject(accountStr);
            accountArray.put(i, accountObject);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    Log.i("", accountArray.toString());

    log的输出为

    四、由多个单个对象的json数组解析为对个单个对象

    多个单个对象组成的json数组解析如下

    // 解析json数组
    List<Account> accountList2 = new ArrayList<Account>();
    for(int i=0;i<accountArray.length(); i++){
        JSONObject jsonObject = null;
        try {
            jsonObject = accountArray.getJSONObject(i);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if(jsonObject != null){
            Account tempAccount = gson.fromJson(jsonObject.toString(), Account.class);
            accountList2.add(tempAccount);
        }
    }
    Log.i("accountList2", accountList2.toString());

    输出的log

    或者用更快捷的转化方法

    Account[] accountArrays = new Gson().fromJson(accountArray.toString(), Account[].class);
    for(int i=0;i<accountArrays.length;i++){
        Log.i("accountArrays",accountArrays[i].toString());
    }
    // 转化为List
    List<Account> foosList = Arrays.asList(accountArrays);

    更快捷地解析成List

    // 更快捷地解析成List
    Type listType = new TypeToken<ArrayList<Account>>(){}.getType();
    ArrayList<Account> accsList = new Gson().fromJson(accountArray.toString(), listType);
    Log.i("accsList",accsList.toString());

    五、生成一个对象嵌套对象的json

    嵌套的json类似如下

    {
        "member": {
            "id": "4",
            "name": "我是传说"
        },
        "id": "4",
        "createDate": "2015-02-02 12:03:32",
        "password": "888888",
        "name": "传说之美"
    }

    生成这个json有2种方法。

    1、再添加一个member类,像添加account类一样添加即可。

    public class Member {
        private String id;
        private String name;
        public Member() {
            super();
        }
        public Member(String id, String name) {
            super();
            this.id = id;
            this.name = name;
        }
        public String getId() {
            return id;
        }
        public void setId(String id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        @Override
        public String toString() {
            return "Member [id=" + id + ", name=" + name + "]
    
    ";
        }
    }

    生成代码如下

    // 生成对象嵌套对象的json
    Account account4 = new Account("4", "888888", "传说之美", sdf.format(new Date()));
    Member member = new Member("4", "我是传说");
    String accountStr = gson.toJson(account4);
    String memberStr = gson.toJson(member);
    JSONObject object = null;
    try {
        JSONObject memberObject = new JSONObject(memberStr);
        object = new JSONObject(accountStr);
        object.put("member", memberObject);    
    } catch (JSONException e) {
        e.printStackTrace();
    }
    Log.i("", object.toString());

    输出的log

    六、解析对象嵌套对象的json 

    Account account5 = gson.fromJson(object.toString(), Account.class);
    Log.i("解析对象嵌套对象的json", account5.toString());
    // 这里用isNull来判断是否存在这个object,存在就拿出member的JSONObject
    JSONObject memberObject = null;
    if(!object.isNull("member")){
        try {
            memberObject = object.getJSONObject("member");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    Member member5 = null;
    if(null != memberObject){
        member5 = gson.fromJson(memberObject.toString(), Member.class);
        Log.i("解析对象嵌套对象的json", member5.toString());
    }

    输出的结果

     7、另外一种解析对象嵌套对象的json 

    定义一个类

    public class AccountObject {
        private String id;
        private String password;
        private String name;
        private String createDate;
        private MemberObject memberObject = new MemberObject();
         
        public class MemberObject {
            private String id;
            private String name;
            @Override
            public String toString() {
                return "MemberObject [id=" + id + ", name=" + name+ "]
    
    ";
            }
        }
        @Override
        public String toString() {
            return "AccountObject [id=" + id + ", password=" + password + ", name=" + name + ", createDate=" + createDate + ","+ memberObject.toString() + "]
    
    ";
        }
    }

    生成json并解析

    try {
        JSONObject mObject = new JSONObject(memberStr);
        object = new JSONObject(accountStr);
        object.put("memberObject", mObject);       
    } catch (JSONException e) {
        e.printStackTrace();
    }
    AccountObject accountObject = gson.fromJson(object.toString(), AccountObject.class);
    Log.i("accountObject", accountObject.toString());

    打印出来的log

    本文博客原创地址:http://www.cnblogs.com/liqw/p/4266209.html

    demo下载链接:http://files.cnblogs.com/files/liqw/LauncherActivity.zip

  • 相关阅读:
    python 集合 set
    Meet Python
    Python 模块
    KNN
    Python Numpy包安装
    R分词
    Maximum Entropy Model(最大熵模型)初理解
    Conditional Random Fields (CRF) 初理解
    Naive Bayes (NB Model) 初识
    Hidden Markov Models(HMM) 初理解
  • 原文地址:https://www.cnblogs.com/zhujiabin/p/7266073.html
Copyright © 2020-2023  润新知