腾讯课堂 —> 尚硅谷Android视频《JSON解析》
Android - 手动解析Json数据(学习笔记一) 一些缺少东西,可参照学习笔记一,本篇较为简略。
导入Gson的jar包
1. 官网下载Gson 2. Gson(2.8.6).jar
把下载好的jar包,复制粘贴到 libs下点击jar包右键,选择Add As Library(添加依赖)
一、将Json对象转换为Java对象
MainActivity2.java
bt1
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v
) {
jsonToJavaObjectByGson();
}
});
private void jsonToJavaObjectByGson() {
String json
= "{\n" +
"\t\"id\":2,\"name\":\"小米煎饼\",\n" +
"\t\"price\":11.2,\n" +
"\t\"imagePath\":\"https://pics3.baidu.com/feed/960a304e251f95caf3db58a3973c4639670952af.jpeg?token=6d173c37740f4bcd401c8c44632b87d6\"\n" +
"}\n";
Gson gson
= new Gson();
ShopInfo shopInfo
= gson
.fromJson(json
, ShopInfo
.class);
tvJson
.setText(json
);
tvJava
.setText(shopInfo
.toString());
}
实现图
二、将Json数组转换为Java集合
MainActivity2.java
bt2
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v
) {
jsonToJavvaListByGson();
}
});
private void jsonToJavvaListByGson() {
String json
= "[\n" +
"\t{\n" +
"\t\t\"id\":1,\"name\":\"小米煎饼\",\n" +
"\t\t\"price\":11.2,\n" +
"\t\t\"imagePath\":\"https://pics3.baidu.com/feed/960a304e251f95caf3db58a3973c4639670952af.jpeg?token=6d173c37740f4bcd401c8c44632b87d6\"\n" +
"\t},\n" +
"\t{\n" +
"\t\t\"id\":2,\"name\":\"芒果干\",\n" +
"\t\t\"price\":10.2,\n" +
"\t\t\"imagePath\":\"https://pics3.baidu.com/feed/960a304e251f95caf3db58a3973c4639670952af.jpeg?token=6d173c37740f4bcd401c8c44632b87d6\"\n" +
"\t}\n" +
"]\n";
Gson gson
= new Gson();
List
<ShopInfo> shops
= gson
.fromJson(json
, new TypeToken<List
<ShopInfo>>() {
}.getType());
tvJson
.setText(json
);
tvJava
.setText(shops
.toString());
}
实现图
三、将Java对象转换为Json对象
MainActivity2.java
bt3
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v
) {
javaToJsonObjectByGson();
}
});
private void javaToJsonObjectByGson() {
ShopInfo shopInfo
= new ShopInfo(1,"小米煎饼",32.0,"xmjb.jpg");
Gson gson
= new Gson();
String json
= gson
.toJson(shopInfo
);
tvJson
.setText(shopInfo
.toString());
tvJava
.setText(json
);
}
实现图
4、将Java集合转换为Json数组
MainActivity2.java
bt4
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v
) {
javaToJsonArrayByGson();
}
});
private void javaToJsonArrayByGson() {
List
<ShopInfo> shops
= new ArrayList<>();
ShopInfo xmjb
= new ShopInfo(1, "小米煎饼", 23.5, "xmjb.jpg");
ShopInfo mgg
= new ShopInfo(2, "芒果干", 22.7, "mgg.jpg");
shops
.add(xmjb
);
shops
.add(mgg
);
Gson gson
= new Gson();
String json
= gson
.toJson(shops
);
tvJson
.setText(shops
.toString());
tvJava
.setText(json
);
}
实现图