我正在使用 Jersey 客户端 1.8 + JAXB。我想发布如下所示的 JSON 有效负载:
{
"transactions": [
{
"amount":
{
"currency":"EUR","total":"1"
}
...
}
],
}
我有一个如下所示的 DTO:
@XmlRootElement
public class PaymentRequestDTO
{
@XmlElement(name="transactions")
public List<TransactionDTO> getTransactions()
{
return transactions;
}
}
当列表仅包含一项交易时,尽管我发布的是:
{
"transactions": {
"amount":
{
"currency":"EUR","total":"1"
}
...
}
}
交易不被视为数组...我花了几个小时来研究这个问题,包括。在 SO 中进行了大量搜索,我读到我必须注册自己的上下文解析器 -> here 。
所以这里是:
@Provider
public class XXXJAXBContextResolver implements ContextResolver<JAXBContext>
{
private JAXBContext context;
private Class<?>[] types = { PaymentRequestDTO.class, TransactionDTO.class, AmountDTO.class };
public XXXJAXBContextResolver() throws Exception
{
this.context = new JSONJAXBContext(JSONConfiguration.natural().build(), types);
}
@Override
public JAXBContext getContext(Class<?> objectType)
{
for (Class<?> type : types)
{
if (type == objectType)
{
return context;
}
}
return null;
}
}
注册本身:
ClientConfig cc = new DefaultClientConfig();
cc.getClasses().add(XXXJAXBContextResolver.class);
client = Client.create(cc);
我使用了所谓的自然表示法:
The natural JSON notation, leveraging closely-coupled JAXB RI integration.
Example JSON expression:
{"columns":[{"id":"userid","label":"UserID"},{"id":"name","label":"User Name"}],"rows":[{"userid":1621,"name":"Grotefend"}]}
Link .
结果仍然相同 - 有效负载中没有数组。我错过了什么吗?
最佳答案
有关信息:
我已经激活了POJO映射(意味着下面使用了jackson),生成的JSON就是我需要的......嗯......
ClientConfig cc = new DefaultClientConfig();
cc.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
关于java - 将自定义 JAXB 上下文与 Jersey 客户端结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30325674/