Java 不同的 JSON 数组响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16518252/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 07:15:23  来源:igfitidea点击:

Different JSON array response

javajsonrestdeserializationgson

提问by Mitja Rogl

I have problems parsing two different JSON responses.

我在解析两个不同的 JSON 响应时遇到问题。

1: This is the JSON response I get from a RESTful API:

1:这是我从 RESTful API 得到的 JSON 响应:

{
  "gear": [
    {
      "idGear": "1",
      "name": "Nosilec za kolesa",
      "year": "2005",
      "price": "777.0"
    }, {
      "idGear": "2",
      "name": "Stresni nosilci",
      "year": "1983",
      "price": "40.0"
    }
  ]
}

2: This response I get from my testing client. I was added some values to the list and then I used gson.toJsonfor testing output.

2:我从我的测试客户那里得到的这个回应。我在列表中添加了一些值,然后用于gson.toJson测试输出。

[
  {
    "idGear": "1",
    "name": "lala",
    "year": 2000,
    "price": 15.0
  }, {
    "idGear": "2",
    "name": "lala2",
    "year": 2000,
    "price": 125.0
  }
]

They are both valid, but the second one was successfully deserialize to object like this:

它们都是有效的,但第二个成功地反序列化为这样的对象:

Type listType = new TypeToken<List<Gear>>() {}.getType();
List<Gear> gears= (List<Gear>) gson.fromJson(json, listType); 

With the first one, I was trying to deserialize the same way but I get error.

对于第一个,我试图以相同的方式反序列化,但出现错误。



EDIT

编辑

API Method:

API方法:

@GET
@Produces(MediaType.APPLICATION_JSON)
public List<Gear> getGear() {
  List<Gear> gears = gearDAO.getGears();
  if (!gears.isEmpty()) {
    return gears;
  } else
    throw new RuntimeException("No gears");
}

CLIENT serialization code:

客户端序列化代码:

List<Gear> list = new ArrayList<Gear>();
Gear o = new Gear();
o.setPrice(15);
o.setYear(2000);
o.setName("asds");
Type listTypes = new TypeToken<List<Gear>>() {}.getType();
gson.toJson(list, listTypes);

采纳答案by MikO

The JSON responses are different!

JSON 响应是不同的!

  • The first one is an object, surrounded by { }, which contains a field "gear"that is in turn a list of objects, surrounded by [ ].

  • The second one is directly a list of objects, because it's surrounded by [ ]. Namely, the whole 2nd response is equivalent to the field in the 1st response.

  • 第一个是一个对象,由 包围{ },其中包含一个字段"gear",该字段又是一个对象列表,由 包围[ ]

  • 第二个是直接的对象列表,因为它被[ ]. 即,整个第二个响应相当于第一个响应中的字段。

So, obviously they can't be parsed in the same way...

所以,显然它们不能以同样的方式解析......

The 2nd one is being parsed correctly because you are using a Listand it is a list. But for the 1st one you need another class that contains a field that contains in turn a list... That is, you just need to create a class structure that represents your JSON responses...

第二个正在被正确解析,因为您使用的是 aList并且它是一个列表。但是对于第一个,您需要另一个包含一个字段的类,该字段又包含一个列表...也就是说,您只需要创建一个表示您的 JSON 响应的类结构...

public class Response {    
    private List<Gear> gears;        
    //getters & setters
}

Now you can parse your 1st response with:

现在您可以解析您的第一个响应:

Gson gson = new Gson();
Response response = gson.fromJson(json, Response .class);
List<Gear> gears = response.getGears();


I suggest you to take a brief look at json.orgin order to understand JSON syntax, which is pretty simple... Basically these are the possible JSON elements:

我建议你简单地看一下json.org以了解 JSON 语法,这非常简单......基本上这些是可能的 JSON 元素:

object
    {}
    { members } 
members
    pair
    pair , members
pair
    string : value
array
    []
    [ elements ]
elements
    value
    value , elements
value
    string
    number
    object
    array
    true
    false
    null