java 獲取json字符串中key對應的值

用到了Gson的JsonParserjson

maven項目引入maven

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

也能夠直接去這個網址下載jar包 https://mvnrepository.com/artifact/com.google.code.gson/gsoncode

咱們來解析下面這個json字符串component

 

 

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);
}
}
最後輸出結果ci

相關文章
相關標籤/搜索