【发布时间】: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 数组,并且对于数组中的每个对象,挑选/提取 event 和 sg_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;
}
}
我在上面的代码 sn-p 中的几个方面苦苦挣扎:
- 如何编写正确的 jsonpath 来指定我的数组中的对象
- 如何从侦听器内部提取
event和sg_event_id值
再说一次,我没有结婚到 JsonSurfer,所以我会采用任何可行的解决方案(Jackson、GSON 等)。但是,我不对以 Jackson 通常的方式将 JSON 映射到 POJO 感兴趣。提前感谢您的所有帮助!
【问题讨论】:
-
“我对像杰克逊通常做的那样将 JSON 映射到 POJO 不感兴趣”的真正含义是什么?你想在这里避免什么,为什么?如果您只想解析出
event和sg_event_id,您绝对可以使用Jackson 以一种非常典型的方式优雅地解决这个问题。
标签: json java-8 jackson jsonpath jsonparser