微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Jackson- 如何处理作为 JSON (Netsed Json) 传递的请求数据?

如何解决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);

另见object mapper javadoc

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?