无法从对象值(令牌' JsonToken.START_OBJECT ')中反序列化类型' [Ljava.lang.Str



我试图将以下JSON解析为POJO,特别是我想提取的有效载荷为字符串[]或字符串列表,而不会丢失JSON格式。

{
"payLoad": [
{
"id": 1,
"userName": null,
"arName": "A1",
"areas": []
},
{
"id": 2,
"userName": "alpha2",
"arName": "A2",
"areas": []
}
],
"count": 2,
"respCode": 200
}

这是我正在使用的POJO -

public class Response {
@JsonProperty("count")
private int totalCount;
@JsonProperty("respCode")
private int responseCode;
@JsonProperty("payLoad")
@JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
private String[] transactionsList;
public String[] getTransactionsList() {
return transactionsList;
}
public void setTransactionsList(String[] transactionsList) {
this.transactionsList = transactionsList;
}
..
}

这是我在springboot中使用的方法,可以自动解析到

public void transactionsReceived() throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
Response responseRcvd = objectMapper.readValue(jsonString, Response.class); 
}

我得到了一个错误-

Exception in thread "main" com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type `[Ljava.lang.String;` from Object value (token `JsonToken.START_OBJECT`)
at [Source: (String)"{"payLoad": [{"id": 1,"userName": null,"arName": "A1","areas": []},{"id": 2,"userName": "alpha2","arName": "A2","areas": []}],"count": 2,"respCode": 200}"; line: 1, column: 14] (through reference chain: com.example.demo.model.Response["payLoad"]->java.lang.Object[][0])
at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:59)
at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1741)..

您可以编写自定义反序列化器:

public class JsonObjectListDeserializer extends StdDeserializer<List<String>> {
public JsonObjectListDeserializer() {
super(List.class);
}
@Override
public List<String> deserialize(JsonParser parser, DeserializationContext context) throws IOException, JacksonException {
JsonNode node = parser.getCodec().readTree(parser);
List<String> result = new ArrayList<>();
if (node.isArray()) {
for (JsonNode element : node) {
result.add(element.toString());
}
} else if (node.isObject()) {
result.add(node.toString());
} else {
//maybe nothing?
}
return result;
}
}

JsonNode.toString()返回节点的json表示,像这样您将节点还原为json以保存在列表中。

然后只为这个特定的字段注册反序列化器。

public static class Response {
@JsonProperty("count")
private int totalCount;
@JsonProperty("respCode")
private int responseCode;
@JsonProperty("payLoad")
@JsonDeserialize(using = JsonObjectListDeserializer.class)
private List<String> transactionsList;
//getters, setters, etc.
}

相关内容

最新更新