【问题标题】:Regarding @JsonAnyGetter, @JsonAnySetter issue关于@JsonAnyGetter,@JsonAnySetter 问题
【发布时间】:2015-01-06 13:49:07
【问题描述】:

我有一个看起来像这样的类:

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class XYZ {

    @JsonSerialize(using = ISODateSerializer.class)
    private Date startDate;
    @JsonSerialize(using = ISODateSerializer.class)
    private Date endDate;
    private Map<String, Object> other = new HashMap<String, Object>();


    @JsonAnyGetter
    public Map<String, Object> any() {
      return other;
    }

    @JsonAnySetter
    public void set(String name, Object value) {
      other.put(name, value);
    }

    @JsonIgnore
    public void setJsonMap(Map<String, Object> other) {
      this.other = other;
    }

}

我还有一个如下所示的 json 输出:

{
  "startDate": "2014-08-23",
  "endDate": "2014-08-24",
  "sumOfOrderValuesSquared": 178,
  "values": [
    {
      "position": 4,
      "value": "your statement closing date in <b>March 2015</b>.",
      "pValue": 0,
      "rawValue": "your statement closing date in <b>March 2015</b>.",
      "calculated": {
        "conversionRateStdErr": 0,
        "visitPercentage": 0.000016899313887856152,
        "conversionRate": 0
      }
    },
     {
      "position": 5,
      "value": "your statement closing date in <b>April 2015</b>.",
      "pValue": 0,
      "rawValue": "ass</b>.",
      "calculated": {
        "conversionRateStdErr": 0,
        "visitPercentage": 0.000012,
        "conversionRate": 0
      }
    }
  ]
}

现在我的问题是我需要遍历“值”对象。它以 arraylist 的形式出现,但我不知道 arraylist 的类型以及如何对其进行迭代,所以我无法对其进行迭代。

还有, 我正在使用 httpClient apache api 进行服务器到服务器的休息调用,但它没有陷入提琴手的陷阱。 我在 Windows 7 机器上使用 java 应用程序。任何想法。 谢谢

【问题讨论】:

  • 你真的应该比初学者更好地设计你的课程。 “一刀切”Map 几乎从来都不是一个好的解决方案。

标签: java json rest jackson fiddler


【解决方案1】:

为数组中的每个值设计一个类,并为它的List 使用实例变量:

private List<Value> values;

Jackson 会自动反序列化。此外,当您使用它时,请为 sumOfValuesSquared 使用另一个实例字段。

此外,您忽略了未知属性,但目前无法忽略任何属性,因为您有一个 JsonAnySetter

但是,如果您真的坚持使用这样的地图,请改用ObjectNode。至少你可以使用JsonNode 可以为你做的一切来导航它。并用@JsonUnwrap注释它。

【讨论】:

  • 是的,我不打算修改课程。我是 JsonNode 的新手,你能详细解释一下如何迭代吗?谢谢
猜你喜欢
  • 2019-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-07
相关资源
最近更新 更多