Jackson- How to process the request data passed as JSON (Netsed Json)?

280 Views Asked by At
{
    "DistributionOrderId" : "Dist_id_1",
    "oLPN": 
    {
        "Allocation": 
        {
            "AID": "12345"      
        },
        "Allocation": 
        {
            "AID": "123456" ,
            "SerialNbr": "SRL001",
            "BatchNbr": "LOT001"
            "RevisionNbr": "RVNBR1"
        }
    },
    "oLPN": 
    {
        "Allocation": 
        {
            "AID": "12123"      
        }
        "Allocation": 
        {
            "AID": "12124"      
        }
    }
}

I have a JSON request passed from the vendor, How to store the values as Java POJO and use them further? Edit : Added attributes to JSON

2

There are 2 best solutions below

5
wanglong On

json key can't repeat, and the repeat key with value will be discard. i have format your json text, may be it is like following expression:

{
    "DistributionOrderId" : "Dist_id_1",
    "oLPN": 
    [
      {
        "Allocation": 
          [
            {
              "AID": "123456" ,
              "SerialNbr": "SRL001",
              "BatchNbr": "LOT001",
              "RevisionNbr": "RVNBR1"
            },
            {
              "AID": "12345"
            }
          ] 
      },
      {
          "Allocation": 
          [
            {
                "AID": "12123"      
            },
            {
                "AID": "12124"      
            }
          ]
      }
    ]
}

and this struct match the java object is

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;
}
2
geco17 On

As you aren't using the usual camel case conventions common in jackson databinding I would suggest defining a java object with the appropriate annotations. The object is not currently valid json. If for example the json looks like this:

{
    "DistributionOrderId" : "Dist_id_1",
    "oLPN": [ ... ]
}

Where each oLPN in the array is an object like this:

{
    "Allocation": [{ "AID": ... }, { "AID": ... }, ... ]
}

You can write a class for distribution orders

public class DistributionOrder {
    @JsonProperty("DistributionOrderId") private String id;
    @JsonProperty("oLPN") private List<OLPN> olpn;
    // getters and setters
}

Then another for the OLPN object

public class OLPN {
    @JsonProperty("Allocation") private String allocation;
    @JsonProperty("AID") private String aid;
    // getters and setters
}

Then you can use an object mapper as appropriate. For example

ObjectMapper mapper = ... // get your object mapper from somewhere

DistributionOrder distributionOrder = mapper.readValue(raw, DistributionOrder.class);

See also object mapper javadoc