使用 JSurfer 或类似工具将 JSON 解析为 Java POJO 列表

Parsing JSON into list of Java POJOs using JSurfer or similar

Java 8 这里,尝试 使用 JSurfer 库,但是我会接受任何有效的有效解决方案。

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

[
  {
    "email": "example@test.com",
    "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": "example@test.com",
    "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 数组,对于数组中的每个对象,cherry pick/extract 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 结婚,所以我将采用任何可行的解决方案(Jackson、GSON 等)。但是,我 有兴趣像 Jackson 通常那样将 JSON 映射到 POJO。在此先感谢您的所有帮助!

使用GSON

public class GsonExample{

    public static void main(String[] args) throws JsonProcessingException {
        List<WebhookEvent> webhookEvents = new Gson().fromJson("YOUR JSON STRING", new TypeToken<List<WebhookEvent>>(){}.getType());
        webhookEvents.forEach(item -> {
            System.out.println(item);
        });
    }
}

class WebhookEvent {

    private String event;
    @SerializedName(value="sg_event_id") // as attribute name in pojo and json are different
    private String sgEventId;

    // getters, setters and ctor omitted for brevity

}

使用Jackson

我不确定你为什么反对使用它。

public class JacksonExample4 {

    public static void main(String[] args) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        List<WebhookEvent> webhookEvents = objectMapper.readValue("YOUR JSON STRING", new TypeReference<List<WebhookEvent>>(){});
        webhookEvents.forEach(item -> {
            System.out.println(item);
        });
    }
}

@JsonIgnoreProperties(ignoreUnknown = true)// To ignore attributes present in json but not in pojo
class WebhookEvent {

    private String event;
    @JsonProperty("sg_event_id")// as attribute name in pojo and json are different
    private String sgEventId;
    // toString() overidden

    // getters, setters and ctor omitted for brevity

}

GSON 和 Jackson 的输出:

WebhookEvent(event=processed, sgEventId=5Gp2JunPL_KgVRV3mqsbcA==) WebhookEvent(event=deferred, sgEventId=KnIgbwNwADlShGoflQ4lTg==)