考虑JSON:
{
"name": "myName",
"myNestedJson": "{\"key\":\"value\"}"
}
应该被解析成类:
public class MyDto {
String name;
Attributes myNestedJson;
}
public class Attributes {
String key;
}
是否可以不用写流解析器解析? (请注意,myNestedJson
包含JSON转义JSON字符串)
我想你可以添加一个构造函数来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是太:)