gson反序列化对象层次结构

时间:2017-08-22 10:31:53

标签: java json serialization gson

我有以下课程:

类:TestClass:

public class TestXClass {

    Map<String, NestedClass> embeddedMap1;
    Map<String, List<NestedClass>> embeddedMap2;

    @Override
    public String toString() {
        return "TestClass [embeddedMap1=" + embeddedMap1 + "(" + embeddedMap1.getClass() + "), embeddedMap2=" + embeddedMap2 + "(" + embeddedMap2.getClass()+ ")]";
    }
}

Class:NestedClass:

public class NestedClass {

    Map<String, Integer> embeddedMap;

    @Override
    public String toString() {
        return "NestedClass [embeddedMap=" + embeddedMap + "("+ 
    embeddedMap.getClass() +")]";
    }
}

我想用gson将TestClass的对象序列化和反序列化为JSON。

这是我的测试代码:

public static void main(String[] args) {
    Gson gson = new GsonBuilder().setPrettyPrinting().create();

    TestClass test = new TestClass();
    test.embeddedMap1 = new HashMap<>();

    NestedClass testNested1 = new NestedClass();
    testNested1.embeddedMap = new HashMap<>();
    testNested1.embeddedMap.put("X", 1);
    test.embeddedMap1.put("A", testNested1);

    List<NestedClass> testNestedList = new ArrayList<>();
    NestedClass listElement = new NestedClass();
    listElement.embeddedMap = new HashMap<>();
    listElement.embeddedMap.put("ABC", 3);
    testNestedList.add(listElement);

    test.embeddedMap2 = new HashMap<>();
    test.embeddedMap2.put("Z", testNestedList);

    String jsonString = gson.toJson(test);

    System.out.println(jsonString);

    TestClass fromJson = gson.fromJson(jsonString, TestClass.class);
    System.out.println(fromJson);
}

Json的序列化工作正常:

{
  "embeddedMap1": {
    "A": {
      "embeddedMap": {
        "X": 1
      }
    }
  },
  "embeddedMap2": {
    "Z": [
      {
        "embeddedMap": {
          "ABC": 3
        }
      }
    ]
  }
}

但是当我尝试将其反序列化为我的TestClass时,我有以下输出:

  

TestClass [embeddedMap1 = {A = NestedClass [embeddedMap = {X = 1}(class   com.google.gson.internal.LinkedTreeMap)]}(类   com.google.gson.internal.LinkedTreeMap),embeddedMap2 = {Z = [NestedClass   [embeddedMap = {ABC = 3}(类   com.google.gson.internal.LinkedTreeMap)]]}(类   com.google.gson.internal.LinkedTreeMap)]

每个地图或列表都被一种gson替换。

如何将这样的对象结构反序列化为普通的java类型?

0 个答案:

没有答案