【问题标题】:Parse JSON with mixed known/unknown fields in JAVA在 JAVA 中使用混合的已知/未知字段解析 JSON
【发布时间】:2017-12-05 06:11:00
【问题描述】:

我有一个简单的 JSON 结构,其中包含已知字段(例如 A 和 B,键入为字符串)和一些未知字段(foo 和 bar,可能还有其他的,或者它们都没有,键入未知)。

[
    {"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 Simple
{
    public String A;
    public String B;
    public HashMap others;
}

【问题讨论】:

  • 你可以改变你的 JSON 结构吗?
  • 我把这个 JSON 作为一个字符串,所以是的,如果它有效的话。 JSON 大约 1 到 5 MB

标签: java json parsing jackson pojo


【解决方案1】:

您可以将 POJO 与 @JsonAnySetter 方法注释一起使用。如果需要,您实际上甚至可以在此方法中执行计算/优化。

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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-23
    • 1970-01-01
    • 1970-01-01
    • 2013-02-21
    • 2016-01-30
    • 1970-01-01
    相关资源
    最近更新 更多