Android数据解析——JSON

时间:2023-09-20 17:10:56

示例一:

有这样一个JSON需要解析,比如:

{
"thresholds": {
"1e-3": 65.3,
"1e-5": 76.5,
"1e-4": 71.8
}
}

希望得到对应的实体类对象。

经过观察,这是一个key-value键值对形式的json字符串,所以定义一个HashMap<String,Double>,然后对其进行反序列化即可。我们使用Gson来进行解析。

在Android Studio中导入jar包,需要两步:

1、在Android Studio中将项目视图切换到Project视图,然后将jar包复制到对应的libs目录下。

Android数据解析——JSON

2、然后在Android Studio中右键,弹出的菜单中选择Add as Library...

Android数据解析——JSON

最终会在gradle中添加对应配置。

Android数据解析——JSON

代码:

 public class Data {
public HashMap<String,Double> thresholds;
}
 Gson gson = new Gson();
String json = "{\n" +
"\"thresholds\": {\n" +
"\"1e-3\": 65.3,\n" +
"\"1e-5\": 76.5,\n" +
"\"1e-4\": 71.8\n" +
"}\n" +
"}";
Data data = gson.fromJson(json, Data.class);

最终得到的data就是我们要的实体类对象。

示例二:

有这样一个JSON需要解析,比如:

{
"category": [
"iOS",
"Android",
"瞎推荐",
"拓展资源",
"福利",
"休息视频"
],
"error": false,
"results": {
"Android": [
{
"_id": "56cc6d23421aa95caa707a69",
"createdAt": "2015-08-06T07:15:52.65Z",
"desc": "类似Link Bubble的悬浮式操作设计",
"publishedAt": "2015-08-07T03:57:48.45Z",
"type": "Android",
"url": "https://github.com/recruit-lifestyle/FloatingView",
"used": true,
"who": "mthli"
}
]
}
}

代码:

public class Data {
public String[] category;
public boolean error;
public Results results;
}
public class Results {
public Android []Android;
}
public class Android {
public String _id;
public String createdAt;
public String desc;
public String publishedAt;
public String type;
public String url;
public boolean used;
public String who;
}
Gson gson = new Gson();
String json = "{\n" +
" \"category\": [\n" +
" \"iOS\",\n" +
" \"Android\",\n" +
" \"瞎推荐\",\n" +
" \"拓展资源\",\n" +
" \"福利\",\n" +
" \"休息视频\"\n" +
" ],\n" +
" \"error\": false,\n" +
" \"results\": {\n" +
" \"Android\": [\n" +
" {\n" +
" \"_id\": \"56cc6d23421aa95caa707a69\",\n" +
" \"createdAt\": \"2015-08-06T07:15:52.65Z\",\n" +
" \"desc\": \"类似Link Bubble的悬浮式操作设计\",\n" +
" \"publishedAt\": \"2015-08-07T03:57:48.45Z\",\n" +
" \"type\": \"Android\",\n" +
" \"url\": \"https://github.com/recruit-lifestyle/FloatingView\",\n" +
" \"used\": true,\n" +
" \"who\": \"mthli\"\n" +
" }\n" +
" ]\n" +
" }\n" +
"}";
Data data = gson.fromJson(json, Data.class);