1.JAVA语法
2.JSON创建
package com.example; import com.google.gson.JsonArray; import com.google.gson.JsonObject; public class MyClass { 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); object.add("lanuage",array); object.addProperty("pop",true); System.out.println(object.toString()); } }
3.JSON读取
package com.example; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import java.io.FileNotFoundException; import java.io.FileReader; public class MyClass { public static void main(String []args){ try { JsonParser jp = new JsonParser(); JsonObject jo = (JsonObject) jp.parse(new FileReader("test.json")); System.out.println("cat="+jo.get("cat").getAsString()); System.out.println("pop="+jo.get("pop").getAsBoolean()); JsonArray ja = jo.get("languages").getAsJsonArray(); for (int i = 0; i < ja.size(); i ++){ JsonObject subJo = ja.get(i).getAsJsonObject(); System.out.println("id="+subJo.get("id").getAsInt()); System.out.println("ide="+subJo.get("ide").getAsString()); System.out.println("name="+subJo.get("name").getAsString()); } } catch (FileNotFoundException e) { e.printStackTrace(); } } }