演示JsonElement对象的deepCopy()、getAsJsonObject()、getAsJsonArray()方法。
import com.google.gson.*; /** * @author yongjar * @date 2020/4/28 */ public class GsonTester { public static void main(String args[]) { Gson gson = new Gson(); //json串 String json = "{ "f1":"Hello","f2":{"f3:":"World"}}"; //解析为json元素 JsonElement j0 = JsonParser.parseString(json); // 方法1: deepCopy() (深度拷贝对象) JsonElement j1 = j0.deepCopy(); boolean equals = j0.equals(j1); System.out.println("拷贝的对象是否相同:" + equals); //方法2: getAsJsonObject() JsonObject asJsonObject = j0.getAsJsonObject(); System.out.println("getAsJsonObject()转化为对象: " + asJsonObject); String json1 = "{ " + ""name":"yongjar", " + ""sex":gender, " + ""sites":[ "Google", "Runoob", "Taobao" ] " + "}"; JsonElement JsonElement = JsonParser.parseString(json1); System.out.println(JsonElement.toString()); //方法3: getAsJsonArray() (转化为数组,前提元素得是数组) //首先得转成json对象 JsonObject asJsonObject1 = JsonElement.getAsJsonObject(); //再获取到key获取到指定的数组。 JsonArray asJsonArray = asJsonObject1.getAsJsonArray("sites"); System.out.println("sites的数组元素是:" + asJsonArray); } }