解析 JSON 与 JAVA 中的混合 known/unknown 字段
Parse JSON with mixed known/unknown fields in JAVA
我有一个简单的 JSON 结构,其中包含已知字段(例如 A 和 B,类型为字符串)和一些未知字段(foo 和 bar,可能还有其他内容,或者 none其中,类型未知)。
[
{"A": "Value for A", B: "Value for B", "foo": "foo"},
{"A": "Value for A", B: "Value for B", "bar": 13},
{"A": "Value for A", B: "Value for B", "foo": "foo", "val": true}
]
我需要将此 JSON 解析为 POJO。
Jackson 允许将此 JSON 解析为 JsonNode,但 JsonNode 在大量数据上占用了太多内存。
有什么解决办法吗?我需要像这样获取 class 的实例:
class Simple
{
public String A;
public String B;
public HashMap others;
}
您可以将 POJO 与 @JsonAnySetter
方法注释一起使用。如果需要,您实际上甚至可以在此方法中执行 computations/optimisations。
public class Simple {
private String A;
private String B;
private Map other = new HashMap<String,Object>();
// "any getter" needed for serialization
@JsonAnyGetter
public Map any() {
return other;
}
// "any setter" needed for deserialization
@JsonAnySetter
public void set(String name, Object value) {
other.put(name, value);
}
// getter and setter for A and B
}
我有一个简单的 JSON 结构,其中包含已知字段(例如 A 和 B,类型为字符串)和一些未知字段(foo 和 bar,可能还有其他内容,或者 none其中,类型未知)。
[
{"A": "Value for A", B: "Value for B", "foo": "foo"},
{"A": "Value for A", B: "Value for B", "bar": 13},
{"A": "Value for A", B: "Value for B", "foo": "foo", "val": true}
]
我需要将此 JSON 解析为 POJO。 Jackson 允许将此 JSON 解析为 JsonNode,但 JsonNode 在大量数据上占用了太多内存。 有什么解决办法吗?我需要像这样获取 class 的实例:
class Simple
{
public String A;
public String B;
public HashMap others;
}
您可以将 POJO 与 @JsonAnySetter
方法注释一起使用。如果需要,您实际上甚至可以在此方法中执行 computations/optimisations。
public class Simple {
private String A;
private String B;
private Map other = new HashMap<String,Object>();
// "any getter" needed for serialization
@JsonAnyGetter
public Map any() {
return other;
}
// "any setter" needed for deserialization
@JsonAnySetter
public void set(String name, Object value) {
other.put(name, value);
}
// getter and setter for A and B
}