Java 如何使用Jackson解析嵌套转义json?
以json为例:Java 如何使用Jackson解析嵌套转义json?,java,json,jackson2,Java,Json,Jackson2,以json为例: { "name": "myName", "myNestedJson": "{\"key\":\"value\"}" } 应解析为类: public class MyDto { String name; Attributes myNestedJson; } public class Attributes { String key; } 在不编写流解析器的情况下可以解析它吗?(请注意,myNestedJson包含json转义json字
{
"name": "myName",
"myNestedJson": "{\"key\":\"value\"}"
}
应解析为类:
public class MyDto {
String name;
Attributes myNestedJson;
}
public class Attributes {
String key;
}
在不编写流解析器的情况下可以解析它吗?(请注意,
myNestedJson
包含json转义json字符串)我认为您可以向属性添加一个构造函数,该构造函数使用字符串
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太脏了:)我认为您可以向属性添加一个构造函数,该构造函数使用字符串
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也太脏了:)对于每个dto构造函数调用,新的ObjectMapper()
是无效的。对于每个dto构造函数调用,新的ObjectMapper()
是无效的。