使用JSurfer或类似方法将JSON解析为Java POJO列表

问题描述 投票:0回答:1

这里是Java 8,trying使用JSurfer库,但是我将接受几乎所有有效的解决方案。

我得到一个包含(例如)以下JSON的字符串:

[
  {
    "email": "[email protected]",
    "timestamp": 1589482169,
    "smtp-id": "<14c5d75ce93.dfd.64b469@ismtpd-555>",
    "event": "processed",
    "category": "cat facts",
    "sg_event_id": "5Gp2JunPL_KgVRV3mqsbcA==",
    "sg_message_id": "14c5d75ce93.dfd.64b469.filter0001.16648.5515E0B88.0"
  },
  {
    "email": "[email protected]",
    "timestamp": 1589482169,
    "smtp-id": "<14c5d75ce93.dfd.64b469@ismtpd-555>",
    "event": "deferred",
    "category": "cat facts",
    "sg_event_id": "KnIgbwNwADlShGoflQ4lTg==",
    "sg_message_id": "14c5d75ce93.dfd.64b469.filter0001.16648.5515E0B88.0",
    "response": "400 try again later",
    "attempt": "5"
  }
]

我想解析JSON数组,并且对于数组中的每个对象,樱桃选择/提取eventsg_event_id字段,并使用它们填充新的WebhookEvent POJO实例。我应该像这样留下List<WebhookEvent>列表:

public class WebhookEvent {

  private String event;
  private String sgEventId;

  // getters, setters and ctor omitted for brevity

}

然后:

public class EventParser {

  private JsonSurfer jsonSurfer = JsonSurferJackson.INSTANCE;

  public List<WebhookEvent> parseJsonToWebhookEventList(String json) {

    List<WebhookEvent> webhookEvents = new ArrayList<>();

    // for each object in the json array, instantiate a pluck out the event/sg_event_id fields
    // into a new WebhookEvent instance, and then add that instance to our list
    SurfingConfiguration surferConfig = jsonSurfer.configBuilder()
      .bind("??? (1) not sure what to put here ???", new JsonPathListener() {
          @Override
          public void onValue(Object value, ParsingContext context) {

              WebhookEvent webhookEvent = new WebhookEvent();
              webhookEvent.setEvent("??? (2) not sure how to pluck this out of value/context ???");
              webhookEvent.setSgEventId("??? (3) not sure how to pluck this out of value/context ???");

              webhookEvents.add(webhookEvent);

          }
      }).build();

      return webhooks;

  }
}

我在上面的代码片段中有些地方挣扎:

  1. 如何编写适当的jsonpath来指定数组中的对象
  2. 如何从侦听器内部提取eventsg_event_id

再次,我不是已婚与JsonSurfer,所以我将采用任何可行的解决方案(杰克逊,GSON等)。但是,我对以杰克逊通常的方式将JSON映射到POJO感兴趣。预先感谢您提供的所有帮助!

Java 8,尝试使用JSurfer库,但是,我将接受几乎所有有效的解决方案。给我一个包含(例如)以下JSON的字符串:[{“ ...
json java-8 jackson jsonpath jsonparser
1个回答
0
投票
您可以通过Jackson轻松完成此操作。我不确定您为什么反对使用它。
© www.soinside.com 2019 - 2024. All rights reserved.