Java Gson 并反序列化包含数组的对象数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3763937/
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-14 04:35:47  来源:igfitidea点击:

Gson and deserializing an array of objects with arrays in it

javajsongson

提问by DavieDave

I am trying to use Gson to deserialize a json string returned from my webservice

我正在尝试使用 Gson 反序列化从我的网络服务返回的 json 字符串

The structure would be returned as TypeDTO[].

该结构将作为 返回TypeDTO[]

where TypeDTOis like

哪里TypeDTO

int id;
String name;
ArrayList<ItemDTO> items[] 

and ItemDTO is like

和 ItemDTO 就像

int id;
String name;
Boolean valid;

When I call the code as follows

当我按如下方式调用代码时

Gson gson = new Gson();
TypeDTO[] mytypes = (TypeDTO[]) gson.fromJson(reply, TypeDTO[].class);

Everything inside the objects is null

对象内的一切都是空的

However, If I use the

但是,如果我使用

JSONArrayand JSONObjectto pull them out piece by piece from the org.json jars, it works fine and the fields are populated accordingly.

JSONArray并将JSONObject它们从 org.json jar 中一块一块地拉出来,它工作正常,并且相应地填充了字段。

Any ideas as to what I'm doing wrong? is Gson extremely fast? Or am I better to stick with what I've got working already?

关于我做错了什么的任何想法?Gson 非常快吗?还是我最好坚持我已经开始的工作?

Thanks, David

谢谢,大卫

采纳答案by Programmer Bruce

The example Java data structure in the original question does not match the description of the JSON structure in the comment.

原始问题中的示例 Java 数据结构与注释中对 JSON 结构的描述不符。

The JSON is described as

JSON 被描述为

"an array of {object with an array of {object}}".

“一个 {object 数组和一个 {object}} 数组”。

In terms of the types described in the question, the JSON translated into a Java data structure that would match the JSON structure for easy deserialization with Gson is

就问题中描述的类型而言,JSON 转换为 Java 数据结构,该数据结构将与 JSON 结构匹配,以便使用 Gson 进行反序列化

"an array of {TypeDTO object with an array of {ItemDTO object}}".

“{TypeDTO 对象数组和 {ItemDTO 对象}} 数组”。

But the Java data structure provided in the question is not this. Instead it's

但是问题中提供的Java数据结构不是这个。而是

"an array of {TypeDTO object with an array of an array of {ItemDTO object}}".

“{TypeDTO 对象数组与 {ItemDTO 对象}} 数组数组”。

A two-dimensional array != a single-dimensional array.

一个二维数组!=一个一维数组。

This first example demonstrates using Gson to simply deserialize and serialize a JSON structure that is "an array of {object with an array of {object}}".

第一个示例演示了使用 Gson 简单地反序列化和序列化一个 JSON 结构,该结构是“{object 数组和 {object}} 数组”。

input.json Contents:

input.json 内容:

[
  {
    "id":1,
    "name":"name1",
    "items":
    [
      {"id":2,"name":"name2","valid":true},
      {"id":3,"name":"name3","valid":false},
      {"id":4,"name":"name4","valid":true}
    ]
  },
  {
    "id":5,
    "name":"name5",
    "items":
    [
      {"id":6,"name":"name6","valid":true},
      {"id":7,"name":"name7","valid":false}
    ]
  },
  {
    "id":8,
    "name":"name8",
    "items":
    [
      {"id":9,"name":"name9","valid":true},
      {"id":10,"name":"name10","valid":false},
      {"id":11,"name":"name11","valid":false},
      {"id":12,"name":"name12","valid":true}
    ]
  }
]

Foo.java:

Foo.java:

import java.io.FileReader;
import java.util.ArrayList;

import com.google.gson.Gson;

public class Foo
{
  public static void main(String[] args) throws Exception
  {
    Gson gson = new Gson();
    TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);
    System.out.println(gson.toJson(myTypes));
  }
}

class TypeDTO
{
  int id;
  String name;
  ArrayList<ItemDTO> items;
}

class ItemDTO
{
  int id;
  String name;
  Boolean valid;
}

This second example uses instead a JSON structure that is actually "an array of {TypeDTO object with an array of an array of {ItemDTO object}}" to match the originally provided Java data structure.

第二个示例使用实际上是“{TypeDTO 对象数组和 {ItemDTO 对象}} 数组的数组”的 JSON 结构来匹配最初提供的 Java 数据结构。

input.json Contents:

input.json 内容:

[
  {
    "id":1,
    "name":"name1",
    "items":
    [
      [
        {"id":2,"name":"name2","valid":true},
        {"id":3,"name":"name3","valid":false}
      ],
      [
        {"id":4,"name":"name4","valid":true}
      ]
    ]
  },
  {
    "id":5,
    "name":"name5",
    "items":
    [
      [
        {"id":6,"name":"name6","valid":true}
      ],
      [
        {"id":7,"name":"name7","valid":false}
      ]
    ]
  },
  {
    "id":8,
    "name":"name8",
    "items":
    [
      [
        {"id":9,"name":"name9","valid":true},
        {"id":10,"name":"name10","valid":false}
      ],
      [
        {"id":11,"name":"name11","valid":false},
        {"id":12,"name":"name12","valid":true}
      ]
    ]
  }
]

Foo.java:

Foo.java:

import java.io.FileReader;
import java.util.ArrayList;

import com.google.gson.Gson;

public class Foo
{
  public static void main(String[] args) throws Exception
  {
    Gson gson = new Gson();
    TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);
    System.out.println(gson.toJson(myTypes));
  }
}

class TypeDTO
{
  int id;
  String name;
  ArrayList<ItemDTO> items[];
}

class ItemDTO
{
  int id;
  String name;
  Boolean valid;
}

Regarding the remaining two questions:

关于剩下的两个问题:

is Gson extremely fast?

Gson 非常快吗?

Not compared to other deserialization/serialization APIs. Gson has traditionally been amongstthe slowest. The current and next releases of Gson reportedly include significant performance improvements, though I haven't looked for the latest performance test data to support those claims.

与其他反序列化/序列化 API 没有比较。GSON历来之中最慢的。据报道,Gson 的当前和下一个版本包括显着的性能改进,尽管我还没有寻找最新的性能测试数据来支持这些说法。

That said, if Gson is fast enough for your needs, then since it makes JSON deserialization so easy, it probably makes sense to use it. If better performance is required, then Hymanson might be a better choice to use. It offers much (maybe even all) of the conveniences of Gson.

也就是说,如果 Gson 足够快满足您的需求,那么由于它使 JSON 反序列化变得如此简单,使用它可能是有意义的。如果需要更好的性能,那么 Hymanson 可能是更好的选择。它提供了 Gson 的许多(甚至全部)便利。

Or am I better to stick with what I've got working already?

还是我最好坚持我已经开始的工作?

I wouldn't. I would most always rather have one simple line of code like

我不会。我总是宁愿拥有一行简单的代码,例如

TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);

...to easily deserialize into a complex data structure, than the thirty lines of code that would otherwise be needed to map the pieces together one component at a time.

...轻松地反序列化为复杂的数据结构,而不是一次将各个部分映射到一个组件所需的 30 行代码。

回答by nagabrahmam

Use your bean class like this, if your JSON data starts with an an array object. it helps you.

如果您的 JSON 数据以数组对象开头,请像这样使用您的 bean 类。它可以帮助你。

Users[] bean = gson.fromJson(response,Users[].class);

Users is my bean class.

用户是我的 bean 类。

Response is my JSON data.

响应是我的 JSON 数据。