我有以下需要解析的JSON代码。我使用相应的JAX-RS模型。问题是paymillClient
对象为空。如果我在currency
对象中添加PaymillSubscription
作为字符串,则返回EUR
值,而不是null。因此PaymillClient
对象似乎存在问题,而不是普通字符串。用于解析的嵌套对象的数量是否有限制? Ex,最多2个嵌套对象。因为在我的案例中有3个,它不起作用。
不幸的是,我无法更改需要解析的JSON代码。我只需要使用JAX-RS实现。
{
"event":{
"event_type":"subscription.succeeded",
"event_resource":{
"subscription":{
"id":"sub_29f144a3bc32c71f96e2",
"offer":{ },
"livemode":false,
"amount":200,
"temp_amount":null,
"currency":"EUR",
"name":"Monthly subscription",
"interval":"1 MONTH",
"trial_start":null,
"trial_end":null,
"period_of_validity":null,
"end_of_period":null,
"next_capture_at":1428939744,
"created_at":1426264944,
"updated_at":1426264944,
"canceled_at":null,
"payment":{ },
"app_id":null,
"is_canceled":false,
"is_deleted":false,
"status":"active",
"client":{
"id":"client_c0c24aa7f97e1b8ed15d"
}
},
"transaction":{ }
},
"created_at":1426264944,
"app_id":null
}
}
PaymillEventContainer:
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class PaymillEventContainer
{
private PaymillEvent event;
}
PaymillEvent:
@XmlAccessorType(XmlAccessType.FIELD)
public class PaymillEvent
{
@XmlElement(name = "event_type") @DocumentationExample(value = "subscription.succeeded") private String eventType;
@XmlElement(name = "event_resource") private PaymillEventResource eventResource;
}
PaymillEventResource:
@XmlAccessorType(XmlAccessType.FIELD)
public class PaymillEventResource
{
private PaymillClient client;
private PaymillOffer offer;
private PaymillSubscription subscription;
}
PaymillSubscription:
@XmlAccessorType(XmlAccessType.FIELD)
public class PaymillSubscription
{
private PaymillClient client;
private PaymillOffer offer;
}
PaymillClient:
@XmlAccessorType(XmlAccessType.FIELD)
public class PaymillClient
{
@DocumentationExample(value = "client_c0c24aa7f97e1b8ed15d") private String id;
}
API端点代码:
public Response postSubscriptionSucceeded(PaymillEventContainer paymillEventContainer)
{
PaymillEvent paymillEvent = paymillEventContainer.getPaymillEvent();
PaymillEventResource paymillEventResource = paymillEvent.getEventResource();
PaymillSubscription paymillSubscription = paymillEventResource.getSubscription();
PaymillClient paymillClient = paymillSubscription.getPaymillClient();
PaymillOffer paymillOffer = paymillSubscription.getPaymillOffer();
String clientId = paymillClient.getId(); // NullPointerException
}
答案 0 :(得分:2)
确定。我试图在你的机器上运行你的代码并且还收到null(注意,我正在使用MOXy来解组JSON)。然后,我试着尝试一下,发现了很有趣的事情:
1.如果你要从你的JSON中删除所有空值字段,所有的工作都很完美。
2.如果您要向PaymillSubscription添加另一个字段。我添加了私人测试测试,测试是:
@XmlAccessorType(XmlAccessType.FIELD)
public class Test {
private String id;
}
并将在订阅对象的最后一个空值字段和“client”字段之间发送此“test”对象:
"test":{"id":"sadas"},
"client":{
"id":"client_c0c24aa7f97e1b8ed15d"
}
然后“test”将为null,但“client”将按预期进行解析。
3.如果要将所有空值对象添加到模型中(我的意思是,在PaymillSubscription类中创建相应的字段),所有工作都是完美的。
看来,默认情况下,JAXB规范不允许JSON使用无法识别的字段,但MOXy仍尝试解析它(有时会产生错误)。