如何解决Jackson- 如何处理作为 JSON (Netsed Json) 传递的请求数据?
{
"distributionorderId" : "dist_id_1","oLPN":
{
"Allocation":
{
"AID": "12345"
},"Allocation":
{
"AID": "123456","SerialNbr": "SRL001","BatchNbr": "LOT001"
"RevisionNbr": "RVNBR1"
}
},"oLPN":
{
"Allocation":
{
"AID": "12123"
}
"Allocation":
{
"AID": "12124"
}
}
}
我有一个来自供应商的 JSON 请求,如何将这些值存储为 Java POJO 并进一步使用它们? 编辑:向 JSON 添加属性
解决方法
json key 不能重复,有 value 的重复 key 会被丢弃。 我已经格式化了您的 json 文本,可能类似于以下表达式:
{
"DistributionOrderId" : "Dist_id_1","oLPN":
[
{
"Allocation":
[
{
"AID": "123456","SerialNbr": "SRL001","BatchNbr": "LOT001","RevisionNbr": "RVNBR1"
},{
"AID": "12345"
}
]
},{
"Allocation":
[
{
"AID": "12123"
},{
"AID": "12124"
}
]
}
]
}
和这个结构匹配的java对象是
class DistributionOrder{
@JsonProperty("DistributionOrderId")
String distributionOrderId;
List<OLPN> oLPN;
}
class OLPN {
@JsonProperty("Allocation")
List<Allocation> allocation;
}
class Allocation{
String AID;
@JsonProperty("SerialNbr")
String serialNbr;
@JsonProperty("BatchNbr")
String batchNbr;
@JsonProperty("RevisionNbr")
String revisionNbr;
}
,
由于您没有使用 jackson 数据绑定中常见的驼峰式大小写约定,我建议使用适当的注释定义一个 java 对象。该对象当前不是有效的 json。例如,如果 json 如下所示:
{
"DistributionOrderId" : "Dist_id_1","oLPN": [ ... ]
}
数组中的每个 oLPN
都是一个这样的对象:
{
"Allocation": [{ "AID": ... },{ "AID": ... },... ]
}
您可以为分销订单编写一个类
public class DistributionOrder {
@JsonProperty("DistributionOrderId") private String id;
@JsonProperty("oLPN") private List<OLPN> olpn;
// getters and setters
}
然后另一个用于 OLPN 对象
public class OLPN {
@JsonProperty("Allocation") private String allocation;
@JsonProperty("AID") private String aid;
// getters and setters
}
然后您可以根据需要使用对象映射器。例如
ObjectMapper mapper = ... // get your object mapper from somewhere
DistributionOrder distributionOrder = mapper.readValue(raw,DistributionOrder.class);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。