Parse a nested JSON using gson

后端 未结 2 936
梦谈多话
梦谈多话 2020-12-04 10:40
{
    \"Response\": {
        \"MetaInfo\": {
            \"Timestamp\": \"2011-11-21T14:55:06.556Z\"
        },
        \"View\": [
            {
                \"         


        
相关标签:
2条回答
  • 2020-12-04 11:26

    If you only need the "PostalCode", you could use JsonParser instead of having a bunch of classes:

    JsonParser jsonParser = new JsonParser();
    JsonObject address = jsonParser.parse(json)
        .getAsJsonObject().get("Response")
        .getAsJsonObject().getAsJsonArray("View").get(0)
        .getAsJsonObject().getAsJsonArray("Result").get(0)
        .getAsJsonObject().get("Location")
        .getAsJsonObject().getAsJsonObject("Address");
    String postalCode = address.get("PostalCode").getAsString();
    

    or for all results:

    JsonArray results = jsonParser.parse(json)
            .getAsJsonObject().get("Response")
            .getAsJsonObject().getAsJsonArray("View").get(0)
            .getAsJsonObject().getAsJsonArray("Result");
    for (JsonElement result : results) {
        JsonObject address = result.getAsJsonObject().get("Location").getAsJsonObject().getAsJsonObject("Address");
        String postalCode = address.get("PostalCode").getAsString();
        System.out.println(postalCode);
    }
    
    0 讨论(0)
  • 2020-12-04 11:28

    To make your Timestamp example work, try:

    public class ParseJSON {
        public static void main(String[] args) throws Exception {
            BufferedReader br = new BufferedReader(new FileReader("try.json"));
    
            Gson gson = new GsonBuilder().create();
            Pojo pojo = gson.fromJson(br, Pojo.class);
    
            System.out.println(pojo.Response.MetaInfo.Timestamp);
            br.close();
        }
    }
    
    class Pojo {
        Response Response = new Response();
    }
    
    class Response {
        MetaInfo MetaInfo = new MetaInfo();
    }
    
    class MetaInfo {
        String Timestamp;
    }
    
    0 讨论(0)
提交回复
热议问题