首页 > 解决方案 > 使用 JSurfer 或类似方法将 JSON 解析为 Java POJO 列表

问题描述

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 数组,并且对于数组中的每个对象,挑选/提取eventsg_event_id字段并使用它们来填充新的WebhookEventPOJO 实例。我应该留下一个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. 如何从侦听器内部提取event和值sg_event_id

同样,我没有与 JsonSurfer结婚,所以我将采用任何可行的解决方案(Jackson、GSON 等)。但是,我对以杰克逊通常的方式将 JSON 映射到 POJO感兴趣。提前感谢您的所有帮助!

标签: jsonjava-8jacksonjsonpathjsonparser

解决方案


使用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

}

使用杰克逊

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

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(事件=已处理,sgEventId=5Gp2JunPL_KgVRV3mqsbcA==) WebhookEvent(事件=延迟,sgEventId=KnIgbwNwADlShGoflQ4lTg==)


推荐阅读