【问题标题】:Java Jackson: Deserialize JSON with dynamic Names into JavaClassJava Jackson:将带有动态名称的 JSON 反序列化为 JavaClass
【发布时间】:2021-09-03 06:22:18
【问题描述】:

我正在尝试使用 jackson 反序列化 JSON。问题是字段名称总是在变化。

这是一个 JSON 示例:

{
 2021-08-02: [
   {
      label: "OnlineGallery",
      nb_uniq_visitors: 1,
      nb_visits: 2,
      nb_events: 2,
      nb_events_with_value: 0,
      sum_event_value: 0,
      min_event_value: 0,
      max_event_value: 0,
      avg_event_value: 0,
      segment: "eventCategory==OnlineGallery",
      idsubdatatable: 1
   }
 ],
 2021-08-03: [ ],
 2021-08-04: [ ]
}

我正在通过 Resttemplate 获取数据并尝试反序列化为 Java 类,但它不起作用:

private EventsGetCategory getEventFromAPI(Date startdate, Date enddate) {
    RestTemplate restTemplate = new RestTemplate();

    DateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd");

    ResponseEntity<EventsGetCategory> response =
        restTemplate.getForEntity(
            matomoUrl + "index.php?module=API&label=OnlineGallery&method=Events.getCategory&secondaryDimension=eventAction&idSite=1&period=day&date=" + dateFormat.format(startdate) + "," + dateFormat.format(enddate) + "&format=JSON&filter_limit=-1"
                + "&token_auth=" + tokenAuth,
            EventsGetCategory.class);

    return response.getBody();
  }

EventsGetCategory 类:

@Data
public class EventsGetCategory {

  @JsonAnySetter
  private Map<String, List<EventDetails>> details;

}

EventDetails 类:

@Data
public class EventDetails {

  String label;
  int nb_uniq_visitors;
  int nb_visits;
  int nb_events;
  int nb_events_with_value;
  int sum_event_value;
  int min_event_value;
  int max_event_value;
  int avg_event_value;
  String segment;
  int idsubdatatable;

}

有人可以帮帮我吗?

【问题讨论】:

    标签: java jackson deserialization json-deserialization spring-resttemplate


    【解决方案1】:

    像这样更新你的EventsGetCategory

    public class EventsGetCategory {
        private Map<String, List<EventDetails>> details;
    
        @JsonAnySetter
        public void setDetails(String key, List<EventDetails> val) {
            if (this.details == null) {
                this.details = new HashMap<>();
            }
            this.details.put(key, val);
        }
    }
    

    【讨论】:

      【解决方案2】:

      如果字段名称总是更改,那么您不能使用 EventDetails 之类的类将 JSON 对象映射到 java 类,而不是 EventDetails 类,您必须使用 Map 来存储动态键价值观。

      【讨论】:

        猜你喜欢
        • 2017-11-29
        • 1970-01-01
        • 2020-12-10
        • 1970-01-01
        • 2023-03-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多