【问题标题】:GSON parsing of google places API谷歌地方API的GSON解析
【发布时间】:2013-05-15 21:38:22
【问题描述】:

我需要一些帮助来创建将填充 GSON 解析器的类。 这是自动完成 Google Places API 的输出:

{
   "predictions" : [
  {
     "reference" : "CjQtAA",
     "terms" : [
        {
           "offset" : 0,
           "value" : "Ladimirevci"
        },
        {
           "offset" : 13,
           "value" : "Hrvatska"
        }
     ],
     "types" : [ "locality", "political", "geocode" ]
  },
  {
     "reference" : "CjQtAAA",
     "terms" : [
        {
           "offset" : 0,
           "value" : "Ladimirevci"
        },
        {
           "offset" : 13,
           "value" : "Hrvatska"
        }
     ],
     "types" : [ "locality", "political", "geocode" ]
  }
],
  "status" : "OK"
}

解决方案感谢MikO

类是:

public class GPlacesAPIResults {

    @SerializedName("predictions")
    public List<GPlacesAPILocation> predictions;

    @SerializedName("status")
    public String status;

}

第二:

public class GPlacesAPILocation implements Serializable {

    private static final long serialVersionUID = 4509808527882750586L;

    @SerializedName("reference")
    private String reference;

    @SerializedName("terms")
    private List<GPlacesAPIAddress> terms;

    @SerializedName("types")
    private List<String> types;

    }

第三:

public class GPlacesAPIAddress implements Serializable {

    private static final long serialVersionUID = -6916297127791361853L;

    @SerializedName("value")
    public String value;

    }

在应用中我这样称呼它

InputStreamReader in = new InputStreamReader(conn.getInputStream()); //results from places api

GPlacesAPIResults lcs = new Gson().fromJson( in , GPlacesAPIResults.class);

感谢您的努力:-)

【问题讨论】:

    标签: java json parsing gson


    【解决方案1】:

    您的 Result 类具有属性 locations 没有任何意义...实际上我不明白您为什么想出这个,因为您的 JSON 中的任何地方都没有 locations 元素!

    尝试这样的事情(按照你的特殊符号):

    Results
    List<Locations> predictions;
    String status;
    
    Locations
    String reference;
    List <Addresses> terms;
    
    Addresses
    String value;
    

    【讨论】:

    • 问题是只有一个预测标签和多个参考/术语对。如果没有 and 对,gson 会崩溃吗?
    • @Reeebuuk:predictions是一个JSON数组(被[ ]包围),所以你必须在List中解析它...数组中元素的数量并不重要,可能有 1 个对象,9999 或 0,在任何情况下,List&lt;Locations&gt; predictions 都将被这些元素填充......然后,这些对象中的每一个(你称之为Locations),反过来,正好有 1 个@ 987654330@ 元素和 1 terms 元素......后者又是一个数组......这个模型应该可以工作!
    • 你是对的。我在 ma Address 类中有 List 值。 :-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-04
    • 2014-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-23
    相关资源
    最近更新 更多