Android 利用Gson生成或解析json

您所在的位置:网站首页 tempaccount Android 利用Gson生成或解析json

Android 利用Gson生成或解析json

2023-06-30 17:01| 来源: 网络整理| 查看: 265

目前手机端和服务端数据交流格式一般是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 + "]\n\n"; } }

定义好这个类,就可以利用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());

看看输出的log

三、生成单个对象的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 accountList = new ArrayList(); 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 accountList2 = new ArrayList(); for(int i=0;i


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3