介绍使用库google-gson库解析json。
"type": "city",
"mark": "true",
"Data":
[{"city": "北京","weather":"雷阵雨","temperature":"31"},
{"city": "上海","weather":"多云","temperature":"30"},
{"city": "天津","weather":"晴","temperature":"33"}]
1、gson-2.3.1的官网链接地址http://search.maven.org/#artifactdetails%7Ccom.google.code.gson%7Cgson%7C2.3.1%7Cjar,点击gson-2.3.1.jar下载后为一个205K的jar包,官网进不去的也可以直接搜索gson-2.3.1.jar进行下载。
2、新建example.json文件,内容如下
{"type": "city",
"mark": "true",
"Data":
[{"city": "北京","weather":"雷阵雨","temperature":"31"},
{"city": "上海","weather":"多云","temperature":"30"},
{"city": "天津","weather":"晴","temperature":"33"}]
}
3、将jar包添加到所使用项目的构建路径。
4、项目中新建ReadJsonContent类来读取example.json文件内容,代码如下
package com.example;
import java.io.FileNotFoundException;
import java.io.FileReader;
import com.google.gson.JsonArray;
import com.google.gson.JsonIOException;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
public class ReadJsonContent {
public static void main(String[] args) {
try {
//新建Json解析器
JsonParser parser = new JsonParser();
//调用parse方法获取到JsonObject
JsonObject object = (JsonObject) parser.parse(new FileReader("example.json"));
//调用一系列get方法获取object的直接子对象
System.out.println("type:"+object.get("type").getAsString());
System.out.println("mark:"+object.get("mark").getAsBoolean());
//新建Json数组获取object的直接子数组
JsonArray array = object.get("Data").getAsJsonArray();
System.out.println("Data:");
//遍历Json数组
for(int i=0;i<array.size();i++)
{
//使用JsonObject获取到数组的元素
JsonObject temp = (JsonObject) array.get(i);
System.out.print(temp.get("city").getAsString()+" ");
System.out.print(temp.get("weather").getAsString()+" ");
System.out.println(temp.get("temperature").getAsInt());
}
} catch (JsonIOException e) {
e.printStackTrace();
} catch (JsonSyntaxException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
得到输出:
5、项目中新建WriteJsonContent类来创建example.json文件内容,附上代码
package com.example;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
public class WriteJsonContent {
public static void main(String[] args) {
JsonObject object = new JsonObject();
object.addProperty("type", "city");
//这里true不加引号会报错
object.addProperty("mark", "true");
JsonArray array = new JsonArray();
JsonObject object1 = new JsonObject();
JsonObject object2 = new JsonObject();
JsonObject object3 = new JsonObject();
//JsonArray第一条数据
object1.addProperty("city", "北京");
object1.addProperty("weather", "雷阵雨");
object1.addProperty("temperature", "31");
//JsonArray第二条数据
object2.addProperty("city", "上海");
object2.addProperty("weather", "多云");
object2.addProperty("temperature", "30");
//JsonArray第三条数据
object3.addProperty("city", "天津");
object3.addProperty("weather", "晴");
object3.addProperty("temperature", "33");
//依次添加数据
array.add(object1);
array.add(object2);
array.add(object3);
object.add("Data", array);
//输出所创建的Json文本
System.out.println(object.toString());
}
}
输出与example.json文件内容一致,只是所有内容都在一行。