NuAlphaMan
NuAlphaMan

Reputation: 713

Json Structure Dynamically Changes in Java

I have a Java microservice and I'm working with an API and it's JSON response dynamically changes. If an order contains one item, it sends the following:

{
    "OrderLines":
    {
        "lineNumber": "1",
        "sku": "12345",
        "quantity": "5",
        "qtyAvail": "15",
        "price": "1.00"
    }
}

But if there are multiple items on an order, it sends the following:

{
    "OrderLines": [
        {
            "lineNumber": "1",
            "sku": "12345",
            "quantity": "5",
            "qtyAvail": "15",
            "price": "1.00"
        },
        {
            "lineNumber": "2",
            "sku": "246810",
            "quantity": "15",
            "qtyAvail": "25",
            "price": "1.15"
        },
        {
            "lineNumber": "3",
            "sku": "3691215",
            "quantity": "2",
            "qtyAvail": "20",
            "price": "2.15"
        }
    ]
}

I haven't seen an API where it changes from a single item to array. Usually, I've received a single item within an array. We're using Jackson to convert the JSON to Java objects. Does anyone know a way to handle this problem? I'm open to using something else if we have to. I just haven't found anything to address this problem. Any help is greatly appreciated.

Upvotes: 1

Views: 46

Answers (1)

Michał Ziober
Michał Ziober

Reputation: 38690

You need to enable DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY feature and root class should look like this:

class RootPojo {

    @JsonProperty("OrderLines")
    private List<OrderLine> orderLines;

    ...
}

Whether it is an array or single object in POJO you should have always a List.

See also:

Upvotes: 1

Related Questions