IT TIP

Gson 및 배열이있는 객체 배열 역 직렬화

itqueen 2020. 11. 21. 08:27
반응형

Gson 및 배열이있는 객체 배열 역 직렬화


Gson을 사용하여 내 웹 서비스에서 반환 된 json 문자열을 역 직렬화하려고합니다.

구조는 TypeDTO[].

경우 TypeDTO처럼

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

ItemDTO는 다음과 같습니다.

int id;
String name;
Boolean valid;

다음과 같이 코드를 호출하면

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

객체 내부의 모든 것이 null입니다.

그러나 내가 사용하는 경우

JSONArray그리고 JSONObject그것을 잘 작동하고 필드 따라 채워의 org.json 단지에서 조각에 의해 조각에서 그들을 끌어합니다.

내가 뭘 잘못하고 있는지에 대한 아이디어가 있습니까? Gson은 매우 빠릅니까? 아니면 내가 이미 일하고있는 것을 고수하는 것이 더 낫습니까?

고마워, 데이비드


원래 질문의 예제 Java 데이터 구조가 주석의 JSON 구조 설명과 일치하지 않습니다.

JSON은 다음과 같이 설명됩니다.

"{object}}의 배열이있는 {object의 배열".

질문에 설명 된 유형과 관련하여 Gson과의 쉬운 역 직렬화를 위해 JSON 구조와 일치하는 Java 데이터 구조로 변환 된 JSON은 다음과 같습니다.

"{ItemDTO object}}의 배열이있는 {TypeDTO 개체의 배열".

그러나 질문에 제공된 Java 데이터 구조는 이것이 아닙니다. 대신 그것은

"{ItemDTO object}} 배열의 배열이있는 {TypeDTO 개체의 배열".

2 차원 배열! = 1 차원 배열.

이 첫 번째 예제는 Gson을 사용하여 "{object}} 배열이있는 {object 배열"인 JSON 구조를 단순히 역 직렬화하고 직렬화하는 방법을 보여줍니다.

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 :

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

이 두 번째 예제는 원래 제공된 Java 데이터 구조와 일치시키기 위해 실제로 "{ItemDTO object}}의 배열이있는 {TypeDTO 객체의 배열"인 JSON 구조를 대신 사용합니다.

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 :

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

나머지 두 가지 질문에 대해 :

Gson은 매우 빠릅니까?

다른 역 직렬화 / 직렬화 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 Jackson might be a better choice to use. It offers much (maybe even all) of the conveniences of 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.


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

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

Users is my bean class.

Response is my JSON data.

참고URL : https://stackoverflow.com/questions/3763937/gson-and-deserializing-an-array-of-objects-with-arrays-in-it

반응형