【问题标题】:Parsing JSON into list of Java POJOs using JSurfer or similar使用 JSurfer 或类似方法将 JSON 解析为 Java POJO 列表
【发布时间】:2020-05-14 21:19:08
【问题描述】:

这里是 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 字段并使用它们来填充新的 WebhookEvent POJO 实例。我应该留下一个List&lt;WebhookEvent&gt; 列表,如下所示:

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;

  }
}

我在上面的代码 sn-p 中的几个方面苦苦挣扎:

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

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

【问题讨论】:

  • “我对像杰克逊通常做的那样将 JSON 映射到 POJO 不感兴趣”的真正含义是什么?你想在这里避免什么,为什么?如果您只想解析出eventsg_event_id,您绝对可以使用Jackson 以一种非常典型的方式优雅地解决这个问题。

标签: json java-8 jackson jsonpath jsonparser


【解决方案1】:

使用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(事件=已处理,sgEventId=5Gp2JunPL_KgVRV3mqsbcA==) WebhookEvent(event=deferred, sgEventId=KnIgbwNwADlShGoflQ4lTg==)

【讨论】:

    猜你喜欢
    • 2011-04-26
    • 1970-01-01
    • 2019-03-01
    • 1970-01-01
    • 2013-02-02
    • 1970-01-01
    • 1970-01-01
    • 2013-03-20
    • 2019-08-17
    相关资源
    最近更新 更多