解析由键“1”、“2”给出的隐式 JSON 列表

Parse implicit JSON list given by keys "1", "2"

我从 API 收到此 JSON。

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

是否可以将其转换为具有以下属性的 java 对象?

我正在使用 jackson-databind ObjectMapper

谢谢!

最好将API,return这个JSON改为return一个包数组。

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

如果无法更改,您将需要通过扩展 StdDeserializer<T> class 来编写自定义反序列化器。您必须以编程方式检查 JsonNode 解析树和 assemble 您想要的对象。

article 解释了如何操作并附带了一个工作代码示例。

我找到了这个可行的解决方案,使用自定义解串器! 我定义了允许的最大包数,但如果不需要,可以删除此检查。

Class 回应:

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 套餐:

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;
    }
}

ClassTestDeserializer(示例):

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());

    }
}

能够使用自定义解串器解决问题。

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;
    }

}

对象如下: 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;
    }
}