1.读取json 代码如下:
public static void main(String[] args) {
JsonParser parser = new JsonParser();
try {
JsonObject object = (JsonObject) parser.parse(new FileReader("test.json"));
System.out.println("code = " + object.get("code").getAsInt());
System.out.println("message = " + object.get("message").getAsString());
JsonArray array = object.get("data").getAsJsonArray();
for (int i = 0; i < array.size(); i++) {
System.out.println("===========================");
JsonObject subObject = array.get(i).getAsJsonObject();
System.out.println("icon = " + subObject.get("icon").getAsString());
System.out.println("name = " + subObject.get("name").getAsString());
System.out.println("detail = " + subObject.get("detail").getAsString());
System.out.println("ptid = " + subObject.get("ptid").getAsString());
System.out.println("url = " + subObject.get("url").getAsString());
}
} catch (JsonIOException | JsonSyntaxException | FileNotFoundException e) {
e.printStackTrace();
}
}
2.创建json,代码如下:
public static void main(String[] args) {
JsonObject object = new JsonObject();
object.addProperty("cat", "it");
JsonArray array = new JsonArray();
JsonObject lan1 = new JsonObject();
lan1.addProperty("id", 1);
lan1.addProperty("name", "Java");
lan1.addProperty("ide", "Eclipse");
array.add(lan1);
JsonObject lan2 = new JsonObject();
lan2.addProperty("id", 2);
lan2.addProperty("name", "Swift");
lan2.addProperty("ide", "Xcode");
array.add(lan2);
JsonObject lan3 = new JsonObject();
lan3.addProperty("id", 3);
lan3.addProperty("name", "C#");
lan3.addProperty("ide", "Visual Studio");
array.add(lan3);
object.add("language", array);
object.addProperty("pop", true);
System.out.println(object.toString());
}