java 获取json字符串中key对应的值

用到了Gson的JsonParser

maven项目引入

<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.3</version>
</dependency>

也可以直接去这个网址下载jar包 https://mvnrepository.com/artifact/com.google.code.gson/gson

我们来解析下面这个json字符串

 

 

Java代码

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;


public class Test {
public static void main(String[] args) {
String resultStr = "{\"status\": 0,\"message\": \"query ok\","+
"\"result\": {\"address\": \"北京市海淀区镜桥\","+
"\"address_component\": {\"nation\": \"中国\",\"province\": \"北京市\","+
"\"city\": \"北京市\",\"district\": \"海淀区\","+
"\"street\": \"镜桥\",\"street_number\": \"镜桥\"}}}";

JsonParser jp = new JsonParser();
//将json字符串转化成json对象
        JsonObject jo = jp.parse(resultStr).getAsJsonObject();
        //获取message对应的值
        String message = jo.get("message").getAsString();
        System.out.println("message:" + message);
        //获取address对应的值
        String address = jo.get("result").getAsJsonObject().get("address").getAsString();
        System.out.println("address:" + address);
        //获取city对应的值
        String nation = jo.get("result").getAsJsonObject().get("address_component")
        .getAsJsonObject().get("nation").getAsString();
        System.out.println("nation:" + nation);
}
}
最后输出结果

 

文章来自:https://www.cnblogs.com/yachao1120/p/11747363.html
© 2021 jiaocheng.bubufx.com  联系我们
ICP备案:鲁ICP备09046678号-3