关于@JsonAnyGetter,@ JsonAnySetter问题

时间:2015-01-06 13:49:08

标签: java json rest jackson fiddler

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

@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进行服务器到服务器的休息调用,但它没有在fiddler中获取陷阱。 我在Windows 7机器上使用java应用程序。任何的想法。 感谢

1 个答案:

答案 0 :(得分:0)

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

private List<Value> values;

杰克逊将自动反序列化。此外,当您使用它时,请使用sumOfValuesSquared的其他实例字段。

此外,您忽略了未知属性,但目前没有属性可以忽略,因为您有JsonAnySetter

但是,如果您真的坚持使用此类地图,请改用ObjectNode。至少你可以使用JsonNode可以为你做的所有事情来导航它。并使用@JsonUnwrap注释它。