有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

要将json对象映射到java对象吗

我正在使用一个特定的API,其json输出如下。我已将其解析为String。 json输出为字符串:{"result":{"number":"INC0022500"}}

正如您所见,它为key result设置了嵌套对象

我正在使用的代码片段将上述json映射到一个对象

Gson gson = new Gson();
EspIncidentTrial staff = gson.fromJson(json, EspIncidentTrial.class);

ESPIncident审判班:

import javax.persistence.Embeddable;

import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonProperty;

@Embeddable
@JsonIgnoreProperties(ignoreUnknown = true)
public class EspIncidentTrial {
    @JsonProperty("result")
    private ResultTrial result;

    public ResultTrial getResult() {
        return result;
    }

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

}

对于嵌套对象,我创建了另一个类ResultTrial。下面是身体

结果分类:

import javax.persistence.Embeddable;

import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonProperty;

@Embeddable
@JsonIgnoreProperties(ignoreUnknown = true)
public class ResultTrial {
    @JsonProperty("number")
    private String incidentId;

    public String getIncidentId() {
        return incidentId;
    }

    public void setIncidentId(String incidentId) {
        this.incidentId = incidentId;
    }
}

现在发生的是,在EspIncidentTrial类中,对象result被映射。然而,在ResultTrial类中,没有进行映射

我试图将json对象中的键result作为字符串处理,但抛出了下面的错误,这是意料之中的

The error occured while parsing the JSON. com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 12 path $.result

请帮忙


共 (0) 个答案