简体   繁体   English

使用GSON的JSON字符串到Java对象

[英]JSON String to Java object using GSON

I am trying to parse json to java. 我试图将json解析为java。

I have the following string that is valid json according to jsonlint.com 根据jsonlint.com,我有以下字符串是有效的json

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" “预计BEGIN_OBJECT但在第1行第2列是BEGIN_ARRAY”

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

BoxSearch consists of this. BoxSearch由此组成。

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. Box是Latitude对象和Longitude对象,它们都是相同的。

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. 我可以将更高级别的属性(lat1,lat2,long1和long2)解析为一个只有4个属性的更简单的BoxSearch对象。 The trouble comes when the json and the object are more complex. 当json和对象更复杂时会出现问题。 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. 我正在运行这个作为junit测试。

Thanks. 谢谢。

Gson gson = new Gson();
gson.fromJson(jsonStr,YourClass.class);

very easy. 很容易。

The reason for the error is that your JSON at the top level is an array, not an object. 出错的原因是顶层的JSON是一个数组,而不是一个对象。 That is covered by GSON throwing "Expected BEGIN_OBJECT but was BEGIN_ARRAY"? 这是由GSON投掷“预期BEGIN_OBJECT但是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. 但是,解决方案不适用于您的JSON,因为您有一个混合类型(对象和数组)的数组,而不是单个类型对象的数组。 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. 为此,您将不得不编写自定义反序列化器(请参阅Gson用户指南的部分内容 )或直接使用Gson的JsonParser类并从解析树中提取数据。

Edit from comments above: 从上面的评论编辑:

If you're the one creating the JSON, it looks like what you want is an array of BoxSearch objects? 如果您是创建JSON的人, 看起来您想要的是一个BoxSearch对象数组?

Based on your Java BoxSearch class, you'd need JSON structured like: 基于您的Java BoxSearch类,您需要JSON结构如下:

[
    {
        "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. 但是,您定义Boxes类的方式不适用于此。 (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: 现在你有一个包含一种类型对象( BoxSearch )的数组,您可以使用它反序列化:

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);

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

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