gpt4 book ai didi

java - 使用jackson进行JSON反序列化

转载 作者:行者123 更新时间:2023-12-02 11:52:49 24 4
gpt4 key购买 nike

我有一个 JSON,我想将其反序列化为 java 对象。我尝试过但没有成功。如果有人帮忙的话真的很感激。我遇到了以下错误。

ObjectMapper mapper = new ObjectMapper();
mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
// Note : vairable 'body' is the JSON string which I've shared below.
RpcResponse rs = mapper.readValue(body, RpcResponse.class);

Exception in thread "main" com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of Result out of START_ARRAY token

{
"error": null,
"id": "12345",
"result": {
"inventory": [{
"history": [{
"when": "2012-08-30T07:28:51Z",
"changes": [{
"removed": "",
"added": "1",
"field_name": "qty"
},
{
"removed": "normal",
"added": "major",
"field_name": "popularity"
}],
"id": 474599,
"alias": null
}]
}

}

这是java类

public class RpcResponse {

private String error;
private String id;
private Map<String, Result> result;

public String getError() {
return error;
}

public void setError(String error) {
this.error = error;
}

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public Result getResult() {
return result;
}

public void setResult(Result result) {
this.result = result;
}

}

public class Result {

private Map<String, List<Inventory>> inventory;

public Map<String, List<Inventory>> getBugs() {
return inventory;
}

public void setBugs(Map<String, List<Inventory>> inventory) {
this.inventory = inventory;
}

}

public class Inventory {

private String id;
private String alias;
private Map<String, List<History>> history;

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public String getAlias() {
return alias;
}

public void setAlias(String alias) {
this.alias = alias;
}

public Map<String, List<History>> getHistory() {
return history;
}

public void setHistory(Map<String, List<History>> history) {
this.history = history;
}

}

public class History {

private String who;
private String when;
private Map<String, Changes> changes;

public String getWho() {
return who;
}
public void setWho(String who) {
this.who = who;
}
public String getWhen() {
return when;
}
public void setWhen(String when) {
this.when = when;
}
public Map<String, Changes> getChanges() {
return changes;
}
public void setChanges(Map<String, Changes> changes) {
this.changes = changes;
}

}

最佳答案

在 RCP 响应中,

private Map<String, Result> result;

应该只是

private Result result;

在结果中,

private Map<String, List<Inventory>> inventory;

应该是

private List<Inventory> inventory;

在库存中,

private Map<String, List<History>> history;

应该是

private List<History> history;

历史上,Map<String,Changes>应该是Collection<Changes>

关于java - 使用jackson进行JSON反序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47776605/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com