将JSON解析为Java中Jackson的Map Map

问题描述 投票:-5回答:2

如何解析JSON,如:

{
  "key1": {
    "subKey1" : {
      "field1": "value",
      "field2": "value"
    },
    "subKey2": {
      "field1": "value",
      "field2": "value"
    }
  },
  "key2": {
    "subKey1" : {
      "field1": "value",
      "field2": "value"
    },
    "subKey2": {
      "field1": "value",
      "field2": "value"
    }
  }
}  

得到像这样的Object结构:

  // key*       subKey*
Map<String, Map<String, DataType>> map;


public class DataType {

    private String field1;
    private String field2;

}

如果这个结构太复杂,至少如何解析DataType的映射?

java json
2个回答
1
投票

解决方案很简单:

ObjectMapper jsonMapper = new ObjectMapper();
TypeReference<Map<String, Map<String, DataType>>> typeRef = 
        new TypeReference<Map<String, Map<String, DataType>>>() {};
Map<String, Map<String, DataType>> configMap = jsonMapper.readValue(strJson, typeRef);

0
投票

我一直在处理同样的问题。我已设法将它变为字符串然后通过使用...手动查找字符串

String string1 = "example of response";
string1.contains(response.body().getAsJsonObject().toString());

另一个替代方法是使用正则表达式(http://www.rexegg.com/regex-quickstart.html)提取你想要用逗号代替字符的字符串,如}和] ...

希望这在某种程度上有所帮助。对不起,这不是很方便

© www.soinside.com 2019 - 2024. All rights reserved.