简体   繁体   English

使用GSON从嵌套JSON检索值

[英]Retrieving values from nested JSON using GSON

I'm working with JSON for the first time and my goal is to make an object with the properties Destination, Origin, and Duration from this JSON result (Google Distance Matrix API) 我是第一次使用JSON,我的目标是根据此JSON结果(Google Distance Matrix API)创建一个具有Destination,Origin和Duration属性的对象

{
   "destination_addresses" : [ "123 High St, Los Angeles, CA 90210, USA" ],
   "origin_addresses" : [ "800 Lake Dr, Los Angeles, CA 90210, USA" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "2.0 km",
                  "value" : 1969
               },
               "duration" : {
                  "text" : "6 mins",
                  "value" : 338
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

So far I have been able to correctly store destination and origin using this line 到目前为止,我已经能够使用此行正确存储目的地和起点
Property data = new Gson().fromJson(json, Property.class); But I am having a very hard time figuring out how to get the values from inside the nests. 但是我很难弄清楚如何从嵌套内部获取值。 Specifically, I'm trying to grab the "text" from duration. 具体来说,我正在尝试从持续时间中获取“文本”。
Any help would be greatly apprciated! 任何帮助将不胜感激!

First create a container for the surrounding data. 首先为周围的数据创建一个容器。

class MainContent
{
  public String destination_addresses;
  public String bar;
  public List<SubContent> subcontent;
}

Then you create a class for the nested data: 然后,为嵌套数据创建一个类:

class SubContent
{
    public String text; 
}

The fields in either classes must have the same names as your json object does. 这两个类中的字段都必须与json对象具有相同的名称。

Then simply: 然后简单地:

gson.fromJson(jsonData, MainContent.class);

GSON will attempt to reflect the values from the json string into the object. GSON将尝试将json字符串中的值反映到对象中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM