【问题标题】:Form pojo to parse JSON形成 pojo 来解析 JSON
【发布时间】:2017-02-24 03:10:40
【问题描述】:

我的 json 看起来像这样:

{
   "bid": "181.57",
   "ask": "181.58",
   "volume": {
       "item1": "543.21",
       "item2": "123.45",
       "timestamp": 1487903100000
   },
   "last": "181.58"
}

我正在尝试使用 spring restTemplate 将其读入 pojo。我现在的pojo是这样的:-

import com.fasterxml.jackson.annotation.JsonProperty;

public class DataModel {
  private String last;

  private Volume volume;

  private String ask;

  private String bid;

  // Getter and setters
}

class Volume
{
    private String timestamp;

    @JsonProperty
    private String item1;

    @JsonProperty
    private String item2;

    // Gettersand setters
}

问题是json中的“item1”和“item2”可以根据我查询的实体更改为“item5”和“item6”。如果我的变量被命名为 item1 和 item2,我会得到空值。如何保留变量 item1 和 item2 的通用名称,并且仍然能够正确读取通用变量中的值?有什么注释可以帮助到这里吗?

【问题讨论】:

  • 你不能将 item5 和 item6 添加到 Volume 类并且总是返回吗?

标签: java spring-boot jackson


【解决方案1】:

我相信这就是您从Baeldung tutorial 寻找的内容:

3.3。 @JsonAnySetter

@JsonAnySetter 允许您灵活地使用 Map 作为标准属性。在反序列化时,来自 JSON 的属性将简单地添加到地图中。

让我们看看它是如何工作的——我们将使用 @JsonAnySetter 来反序列化实体 ExtendableBean:

public class ExtendableBean {
    public String name;
    private Map<String, String> properties;

    @JsonAnySetter
    public void add(String key, String value) {
        properties.put(key, value);
    }
}

这是我们需要反序列化的 JSON:

{
    "name":"My bean",
    "attr2":"val2",
    "attr1":"val1"
}

这就是这一切如何联系在一起的:

@Test
public void whenDeserializingUsingJsonAnySetter_thenCorrect()
  throws IOException {
    String json
      = "{\"name\":\"My bean\",\"attr2\":\"val2\",\"attr1\":\"val1\"}";

    ExtendableBean bean = new ObjectMapper()
      .readerFor(ExtendableBean.class)
      .readValue(json);

    assertEquals("My bean", bean.name);
    assertEquals("val2", bean.getProperties().get("attr2"));
}

在您的情况下,您只需在地图上查询您所期望的任何查询的字符串值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-13
    • 2021-06-02
    • 2013-02-02
    • 2018-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多