使用GSON将JSON字符串转换为Java对象 [英] JSON String to Java object using GSON

查看:157
本文介绍了使用GSON将JSON字符串转换为Java对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有以下字符串,根据jsonlint.com是有效的json。



pre $私人最终静态字符串LOC_JSON =
[
+{
+\lat1\: 39.737567,
+\lat2 \:32.7801399,
+\long1\:-104.98471790000002,
+\long2 \ :-96.80045109999998
+},
+[
+{
+\lat\:{
+\b\:38.88368709500021,
+\d \:40.620468491667026
+},
+\long \ :{
+\b\:-105.75306170749764,
+\d\:-104.675854661387
+}
+}
+]
+];

我试图将它解析为一个对象,并且出现以下错误。
期望的BEGIN_OBJECT,但在BEGIN_ARRAY在第1行第2列

  Gson gson = new Gson(); 
BoxSearch b = gson.fromJson(LOC_JSON,BoxSearch.class);

BoxSearch由此组成。

 私人数字lat1; 
私人数字lat2;
私人号码long1;
私人号码long2;
私人包厢[]箱;

Boxes是一个Latitude对象和一个Longitude对象,它们都被定义为相同。

  private String b; 
私人字符串d;

我可以将更高级别的属性(lat1,lat2,long1和long2)解析为更简单的BoxSearch只有这4个属性的对象。当json和对象更复杂时,麻烦就来了。是否有可能做我正在尝试的?



我希望我已经提供了足够的信息来获得一些帮助。如果需要,我会很乐意提供更多信息,甚至是测试项目。



谢谢。 解决方案

错误的原因是你的顶层JSON是一个数组,而不是一个对象。这是由 GSON投掷预计BEGIN_OBJECT,但是BEGIN_ARRAY? 。然而,这个解决方案不适合你的JSON,因为你有一个混合类型的数组(一个对象和一个数组),而不是单一类型对象的数组。为此,您将不得不编写自定义反序列化器(请参阅 Gson用户指南的部分内容)或者使用Gson的 JsonParser 课程,然后提取来自分析树的数据。



编辑上述注释: 如果您是创建JSON,它看起来像你想要的是一个 BoxSearch 对象的数组?



基于您的Java BoxSearch 类,您需要JSON结构如下:

  [
{
lat1:39.737567,
lat2:32.7801399,
long1 :-104.98471790000002,
long2:-96.80045109999998,
boxes:[
{
lat:{
b:38.88368709500021,
d:40.620468491667026
},
长:{
b:-105.75306170749764,
d:-104.675854661387
}




code>

然而,你有 Boxes 类定义的方法对此不起作用。 (你的意思是有一系列的?)。原因是它需要如下所示:

  class Boxes {
Box lat;
@SerializedName(long)
Box lon;
}

class Box {
String b;
字符串d;



$ b现在你有一个数组包含一种类型的对象( BoxSearch ),您可以反序列化:

 类型collectionType = new TypeToken< Collection< BoxSearch> >(){}的getType(); 
收藏< BoxSearch> boxSearchCollection = gson.fromJson(json,collectionType);

如果你真的不需要这些数组,就干掉外层数组:

  gson.fromJson(json,BoxSearch.class); 


I am trying to parse json to java.

I have the following string that is valid json according to jsonlint.com

private final static String LOC_JSON = 
         "["
        +"{"
        +"  \"lat1\": 39.737567,"
        +"  \"lat2\": 32.7801399,"
        +"  \"long1\": -104.98471790000002,"
        +"  \"long2\": -96.80045109999998"
        +"},"
        +"  ["
        +"      {"
        +"          \"lat\": {"
        +"              \"b\": 38.88368709500021,"
        +"              \"d\": 40.620468491667026"
        +"          },"
        +"          \"long\": {"
        +"          \"b\": -105.75306170749764,"
        +"          \"d\": -104.675854661387"
        +"          }"
        +"      }"
        +"  ]"
        +"]";

I am trying to parse it into an object and I get the following error. "Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2"

            Gson gson = new Gson();
        BoxSearch b = gson.fromJson( LOC_JSON, BoxSearch.class ); 

BoxSearch consists of this.

private Number lat1;
private Number lat2;
private Number long1;
private Number long2;
private Boxes[] boxes;

Boxes is a Latitude object and a Longitude object which are both defined identical.

private String b;
private String d;

I can parse the higher level attributes (lat1,lat2,long1 and long2) into a more simple BoxSearch object that only has those 4 attributes. The trouble comes when the json and the object are more complex. Is it even possible to do what I am trying?

I hope I have provided enough information to get some help. I would be happy to provide more info or even a test project if need be. I am running this as a junit test.

Thanks.

解决方案

The reason for the error is that your JSON at the top level is an array, not an object. That is covered by GSON throwing "Expected BEGIN_OBJECT but was BEGIN_ARRAY"?.

However, the solution there won't work for your JSON because you have an array of mixed types (an object and an array) rather than an array of a single type of object. For that you're going to have to write a custom deserializer (See The section of the Gson user's guide that covers this) or use Gson's JsonParser class directly and extract the data from the parse tree.

Edit from comments above:

If you're the one creating the JSON, it looks like what you want is an array of BoxSearch objects?

Based on your Java BoxSearch class, you'd need JSON structured like:

[
    {
        "lat1" : 39.737567,
        "lat2" : 32.7801399,
        "long1" : -104.98471790000002,
        "long2" : -96.80045109999998,
        "boxes" : [ 
                    {
                      "lat": {
                          "b": 38.88368709500021,
                          "d": 40.620468491667026
                      },
                      "long": {
                          "b": -105.75306170749764,
                          "d": -104.675854661387
                      }
                    }
                  ]
    }
]

However, the way you have Boxes class defined won't work for that. (Did you mean to have an array of them?). As-is it would need to look like:

class Boxes {
    Box lat;
    @SerializedName("long")
    Box lon;
}

class Box {
   String b;
   String d;
}

Now you have an array containing one type of object (BoxSearch) which you could deserialize with:

Type collectionType = new TypeToken<Collection<BoxSearch>>(){}.getType();
Collection<BoxSearch> boxSearchCollection = gson.fromJson(json, collectionType);

If you really don't need an array of these, get rid of the outer array and simply do:

gson.fromJson(json, BoxSearch.class);

这篇关于使用GSON将JSON字符串转换为Java对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆