import com.google.gson 谷歌的gson包
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
解析json字符串可以像解析DOM一样,解析每一个节点。Gson的jar包中提供了JsonParser类,专门用于解析json字符串的,注意只是json节点的内容解析出来
public static void main(String[] args) {
String jsonString = "{\"id\":1, \"name\":\"lzj\", \"cars\":[\"audi\", \"baoma\", \"benci\"]}";
JsonParser parser = new JsonParser();
JsonElement parse = parser.parse(jsonString);
if (parse.isJsonObject()){
JsonObject asJsonObject = parse.getAsJsonObject();
JsonElement name = asJsonObject.get("name");
String asString = name.getAsString();
System.out.println("asString"+asString);
JsonArray cars = asJsonObject.getAsJsonArray("cars");
cars.forEach(a->{
System.out.println(a);
});
}
}