Home > Software engineering >  Parse implicit JSON list given by keys "1", "2"
Parse implicit JSON list given by keys "1", "2"

Time:11-05

I'm receiving this JSON from an API.

{
    "message" : "message",
    "1": {
        "packageCode": "packageCode1",
        "packageNum": "packageNum1"
    },
    "2": {
        "packageCode": "packageCode2",
        "packageNum": "packageNum2"
    }
}

Is it possible to convert it to a java object with the below attributes?

  • String message
  • Package [] packages

I'm using jackson-databind ObjectMapper.

Thank you!

CodePudding user response:

It is better to change the API, which returns this JSON to return an array of packages.

{
    "message" : "message",
    "packages": [
    {
        "packageCode": "packageCode1",
        "packageNum": "packageNum1"
    },
    {
        "packageCode": "packageCode2",
        "packageNum": "packageNum2"
    }]
}

If this cannot be changed, you'll need to write a custom deserealizer by extending the StdDeserializer<T> class. You'll have to programmatically inspect the JsonNode parse tree and assemble the object that you want.

This article explains how to do it and comes with a working code sample.

CodePudding user response:

I found this working solution, using a custom deserializer! I defined a max number of allowed packages, but this check can be removed, if not necessary.

Class Response:

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

    @Getter
    @Setter
    @ToString
    @JsonDeserialize(using = ResponseDeserializer.class)
    public class Response {
    
        private String message;
        private Package [] packages;
    }

Class Package:

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@Getter
@Setter
@ToString
public class Package {

    private String packageCode;
    private String packageNum;
}

Class ResponseDeserializer:

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;

public class ResponseDeserializer extends StdDeserializer<Response> {

    private static final long serialVersionUID = -6665611685508708642L;
    private static final long MAX_PACKAGE_NUM = 1000;
    private ObjectMapper objectMapper = new ObjectMapper();

    public ResponseDeserializer() {
        this(null);
    }

    public ResponseDeserializer(Class<?> vc) {
        super(vc);
    }

    @Override
    public Response deserialize(JsonParser parser, DeserializationContext ctx)
            throws IOException {
        final JsonNode node = parser.getCodec().readTree(parser);
        final String message = node.get("message").asText();
        final List<Package> packageList = new ArrayList<>();
        for (var key = 1; key < MAX_PACKAGE_NUM; key  ) {
            var packageNode = node.get(String.valueOf(key));
            if (null == packageNode) {
                break;
            }
            var currentPackage = objectMapper.treeToValue(packageNode, Package.class);
            packageList.add(currentPackage);
        }
        final var response = new Response();
        response.setMessage(message);
        response.setPackages(packageList.toArray(new Package[0]));
        return response;
    }
}

Class TestDeserializer (sample):

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class TestDeserializer {

    public static void main(String[] args) throws JsonMappingException, JsonProcessingException {
        String responseJSON = """
                                {
                    "message" : "message",
                    "1": {
                        "packageCode": "packageCode1",
                        "packageNum": "packageNum1"
                    },
                    "2": {
                        "packageCode": "packageCode2",
                        "packageNum": "packageNum2"
                    }
                }

                                """;
        Response response = new ObjectMapper().readValue(responseJSON, Response.class);
        System.out.println(response.toString());

    }
}

CodePudding user response:

Was able to solve using the custom deserializer.

package com.test.json;

import java.io.IOException;
import java.util.ArrayList;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;

public class TestJsonObjectDeserializer extends StdDeserializer<TestJsonObject> {

    private static final long serialVersionUID = 1L;

    public TestJsonObjectDeserializer() {
        this(null);
    }

    protected TestJsonObjectDeserializer(Class<?> vc) {
        super(vc);
    }

    @Override
    public TestJsonObject deserialize(JsonParser jsonParser, DeserializationContext arg1) throws IOException, JsonProcessingException {
        TestJsonObject testJsonObject = new TestJsonObject();
        JsonNode jsonNode = jsonParser.getCodec().readTree(jsonParser);
        String message = jsonNode.get("message").textValue();
        ArrayList<Package> packages = new ArrayList<Package>();
        if (message != null) {
            testJsonObject.setMessage(message);
            int i = 1;
            Package package1 = null;
            do {
                package1 = null;
                JsonNode pkg = null;
                if (jsonNode.get(String.valueOf(i)) != null) {
                    pkg = jsonNode.get(String.valueOf(i));
                    String packageCode = pkg.get("packageCode").textValue();
                    String packageNum = pkg.get("packageNum").textValue();
                    package1 = new Package();
                    package1.setPackageCode(packageCode);
                    package1.setPackageNum(packageNum);
                }
                i  ;
                if (package1 != null) {
                    packages.add(package1);
                }
            } while (package1 != null);

            if (!packages.isEmpty()) {
                Package[] packages1 = new Package[packages.size()];
                testJsonObject.setPackages(packages.toArray(packages1));
            }
            return testJsonObject;
        }
        return null;
    }

}

here are the objects: Package.java

package com.test.json;

public class Package {
    protected String packageCode;
    protected String packageNum;

    public String getPackageCode() {
        return packageCode;
    }

    public void setPackageCode(String packageCode) {
        this.packageCode = packageCode;
    }

    public String getPackageNum() {
        return packageNum;
    }

    public void setPackageNum(String packageNum) {
        this.packageNum = packageNum;
    }

    @Override
    public String toString() {
        return "Package [packageCode="   packageCode   ", packageNum="   packageNum   "]";
    }
}

TestJsonObject:

package com.test.json;

import java.util.Arrays;

public class TestJsonObject {
    protected String message;
    protected Package[] packages;

    public String getMessage() {
        return message;
    }

    @Override
    public String toString() {
        return "TestJsonObject [message="   message   ", packages="   Arrays.toString(packages)   "]";
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Package[] getPackages() {
        return packages;
    }

    public void setPackages(Package[] packages) {
        this.packages = packages;
    }
}
  • Related