【问题标题】:How to deserialize the String which is array of objects to a array of objects?如何将作为对象数组的字符串反序列化为对象数组?
【发布时间】:2022-01-24 05:43:52
【问题描述】:

我有一个响应正文

[{"vendorName":"ABC","vendorAPI":"Some_API","enrichmentGroupingLevel":[{"Test":{"score":0.233,"risckscore":229},"level":"all"}],"error":{},"statusCode":200}]",
CoreV2Response[] getEnrichmentResponse = objectMapper.readValue(responseBody, CoreV2Response[].class);

下面是我想要映射的 coreV2Response 类

public class CoreV2Response {
            @JsonProperty("vendorName")
            private String vendorName;
            @JsonProperty("vendorAPI")
            private String vendorAPI;
            @JsonProperty("enrichmentGroupingLevel")
            private Object[] enrichmentGroupingLevel;
            @JsonProperty("error")
            private Object[] error;
            @JsonProperty("statusCode")
            private int statusCode;
        }
I am getting error 
Cannot deserialize instance of [Ljava.lang.Object; out of START_OBJECT tokenat [Source: (String)"[{"vendorName":"Ekata","vendorAPI":"Account_Opening_V1.0","enrichmentGroupingLevel
```
 
Can someone help me with deserialization?
I have added my both the codes for response template class and mapper object

【问题讨论】:

    标签: java json


    【解决方案1】:

    在您的 json 字符串中,错误在对象中

    "error": {}
    

    但在 CoreV2Response 中,您已将 error 字段声明为对象数组:

    private Object[] error;
    

    在您的情况下,您不能将 json 对象反序列化为集合、数组。您必须将错误声明为对象

    private Object error;
    

    反序列化没有问题。

    【讨论】:

    • 我可以像这样通过 getEnrichmentResponse.getvendorName 访问类中的每个变量吗?
    • @krishnagiri2000 我不确定我是否理解这个问题。如果您询问如何访问错误的数据,由于该字段被声明为Object,因此它被反序列化为Map<String, Object>,因此您需要强制转换为Map并使用map提供的方法来访问其中的数据。
    • 考虑到响应主体是一个字符串,它是一个对象数组,我是否正确调用了对象映射器类的方法?
    • @krishnagiri2000 是的,像这样调用对象映射器 - CoreV2Response[] getEnrichmentResponse = objectMapper.readValue(responseBody, CoreV2Response[].class); 在您的情况下是绝对正确的。唯一的错误是我在回答中写的,其他一切都是正确的。
    • @krishnagiri2000 是的,这是其中一种方法,而且是正确的方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-14
    • 2017-08-24
    • 2016-09-06
    相关资源
    最近更新 更多