简体   繁体   English

反序列化复杂的gson-Java

[英]Deserialize complex gson - Java

I have an array of objects which are like below. 我有一个对象数组,如下所示。

{
  "propone": {
    "proponeone": {
      "a": 1,
      "b": 1,
      "c": 1
    },
    "proponetwo": {
      "a": 1
    },
    "proponethree": {
      "a": 1,
      "b": 1
    },
    "proponethree": {
      "a": 1,
      "b": 1,
      "c": 1
    }
  },
  "proptwo": {
    "proptwoone": [
      "val1",
      "val2",
      "val3",
      "val4"
    ],
   "proptwoone": [
      "val5",
      "val6",
      "val7"
    ]
  }
}

I read this array to a JsonObject and I want to deserialize this array of objects. 我将此数组读取到JsonObject,并想反序列化此对象数组。 I want to put "proptwoone" in to a HashMap of type <String, ArrayList<String>> . 我想将“ proptwoone”放入类型为<String, ArrayList<String>>HashMap中。 Is there a way to do that? 有没有办法做到这一点? I use Gson. 我用格森。

If your JSON's structure will be always like that, you can try to create a class like this, using a generic Object for that part you're not interested in: 如果您的JSON的结构总是这样,则可以尝试对不感兴趣的部分使用通用Object来创建类似的类:

public class Response {
  public Object propone;
  public HashMap<String, ArrayList<String>> proptwo;
}

Then just parse your JSON with: 然后只需解析您的JSON:

Response response = gson.fromJson(yourJsonString, Response.class);

And your HashMap will be under: 您的HashMap将位于以下位置:

response.proptwo

But I guess this won't work if you have duplicated field names proptwoone ... 但是我想如果您重复字段名称proptwoone这将proptwoone ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM