考虑json:
{
"name": "myName",
"myNestedJson": "{\"key\":\"value\"}"
}
应解析为类:
public class MyDto {
String name;
Attributes myNestedJson;
}
public class Attributes {
String key;
}
是否可以在不编写流解析器的情况下对其进行解析? (请注意,myNestedJson
包含json转义的json字符串)
答案 0 :(得分:0)
我认为您可以向Attributes
添加一个String
的构造函数
class Attributes {
String key;
public Attributes() {}
public Attributes(String s) {
// Here, s is {"key":"value"} you can parse it into an Attributes
// (this will use the no-arg constructor)
try {
ObjectMapper objectMapper = new ObjectMapper();
Attributes a = objectMapper.readValue(s, Attributes.class);
this.key = a.key;
} catch(Exception e) {/*handle that*/}
}
// GETTERS/SETTERS
}
然后您可以通过以下方式对其进行解析:
ObjectMapper objectMapper = new ObjectMapper();
MyDto myDto = objectMapper.readValue(json, MyDto.class);
这有点脏,但是您原来的JSON也很:)