本文介绍了GSON序列化子对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要序列化此JSON结构:

I want to serialize this JSON structure :

{
   "name":"name 1",
   "number":1,
   "standing":[
      {
         "subRank":1,
         "subname":"test"
      },
      {
         "subRank":2,
         "subname":"Test2"
      }]
}

我想使用这样的对象关联:

And I want to use an object association like that :

public class ParentClass{
    String name;
    String number;
    List<SubClass> SubClassList;
}

public class SubClass{
    String subRank;
    String subname;
}

我尝试使用以下代码:

Type type = new TypeToken<List<ParentClass>>() {}.getType();
ArrayList<ParentClass> parentClassList= new ArrayList<>();
parentClassList= gson.fromJson(jsonContent, type);

但是我有这个例外:

感谢您的帮助:)

推荐答案

我这样解决案件:

JSON :

{
   "name":"name 1",
   "number":1,
   "standing":[
      {
         "subRank":1,
         "subname":"test"
      },
      {
         "subRank":2,
         "subname":"Test2"
      }]
}

POJO :

public class ParentClass{
    String name;
    int number;
    List<SubClass> standing;
}

public class SubClass{
    int subRank;
    String subname;
}

JAVA :

Gson gson = new Gson();
Type type = new TypeToken<ParentClass>() {}.getType();
ParentClass parentClassList= gson.fromJson(data, type);

非常感谢@ Emre,@ Christoph-Tobias Schenke和@Davide Patti

Thanks very much @Emre, @Christoph-Tobias Schenke and @Davide Patti

这篇关于GSON序列化子对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 13:20