Gson JsonParser用于将 Json 数据解析为JsonElement并因此解析为JsonObject的解析树。 JsonObject可用于使用 JSON 字符串中的相应键来访问值。
1.创建JsonParser
JsonParser类只有一个默认的构造器,不需要任何参数或配置。
JsonParser parser = new JsonParser();
2.解析 JSON
JsonParser类提供 3 种方法来提供 JSON 作为源并将其解析为JsonElement的树。
- JsonElement parse(JsonReader json)– 使用- JsonReader将 JSON 作为令牌流读取,并从 JSON 流中返回下一个值作为分析树。
- JsonElement parse(java.io.Reader json)– 使用指定的读取器读取 JSON,并将 JSON 字符串解析为解析树。
- JsonElement parse(java.lang.String json)- 将指定的 JSON 字符串解析为解析树。
如果指定的文本不是有效的 JSON,则这三种方法都将抛出JsonParseException和JsonSyntaxException。
3. JsonElement,JsonObject和JsonArray
在JsonElement树中解析了 JSON 字符串后,我们就可以使用它的各种方法来访问 JSON 数据元素。
例如,使用一种类型检查方法找出它代表什么类型的 JSON 元素:
jsonElement.isJsonObject();
jsonElement.isJsonArray();
jsonElement.isJsonNull();
jsonElement.isJsonPrimitive();
我们可以使用相应的方法将JsonElement转换为 JsonObject和JsonArray:
JsonObject jsonObject = jsonElement.getAsJsonObject();
JsonArray jsonArray = jsonElement.getAsJsonArray();
一旦有了JsonObject或JsonArray实例,就可以使用其 get()方法从中提取字段。
4. Gson JsonParser示例
使用JsonParser的 Java 程序将 JSON 解析为 JsonElement(和JsonObject),并使用键获取 JSON 值。
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class Main
{
public static void main(String[] args) throws Exception
{
String json = "{'id': 1001, "
+ "'firstName': 'Lokesh',"
+ "'lastName': 'Gupta',"
+ "'email': 'howtodoinjava@gmail.com'}";
JsonElement jsonElement = new JsonParser().parse(json);
JsonObject jsonObject = jsonElement.getAsJsonObject();
System.out.println( jsonObject.get("id") );
System.out.println( jsonObject.get("firstName") );
System.out.println( jsonObject.get("lastName") );
System.out.println( jsonObject.get("email") );
}
}
程序输出。
1001
"Lokesh"
"Gupta"
"howtodoinjava@gmail.com"
5.使用fromJson()获得JsonObject
我们可以使用Gson实例和来自Json()方法的实例来达到相同的结果。
String json = "{'id': 1001, "
+ "'firstName': 'Lokesh',"
+ "'lastName': 'Gupta',"
+ "'email': 'howtodoinjava@gmail.com'}";
JsonObject jsonObject = new Gson().fromJson(json, JsonObject.class);
System.out.println(jsonObject.get("id"));
System.out.println(jsonObject.get("firstName"));
System.out.println(jsonObject.get("lastName"));
System.out.println(jsonObject.get("email"));
程序输出:
1001
"Lokesh"
"Gupta"
"howtodoinjava@gmail.com"
将有关使用Jsonparser从 Java 的 json 字符串中获取值的问题交给我。
学习愉快!
 
                         
                                

