代码之家  ›  专栏  ›  技术社区  ›  bibliophilsagar

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

  •  0
  • bibliophilsagar  · 技术社区  · 7 年前

    String . json输出为字符串: {"result":{"number":"INC0022500"}} .

    result .

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

    ESPIncidentTrial课程:

    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 后果 结果试验 类,没有进行映射。

    后果 在json对象中作为字符串,但抛出了以下错误,这是意料之中的。

    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
    

    请帮忙!

    2 回复  |  直到 7 年前
        1
  •  1
  •   Sachin Gupta    7 年前

    给你混合 gson Jackson 您正在使用的注释 杰克逊 GSON's 方法将其反序列化。

    使用 Jackson's objectMapper

    ObjectMapper mapper = new ObjectMapper();
    EspIncidentTrial staff = mapper.readValue(json, EspIncidentTrial.class);
    
        2
  •  0
  •   Rinku Jagdale    7 年前

    你可以试试这个。。。。

    String searchdata=“{userPojo\”:{“userid\”:1156}}}”;

    if(searchdata.contains(“userPojo”))

    {

    字符串jsonstring=jsonObject。getString(“userPojo”);

    UserPojo UserPojo=gson。fromJson(searchdata,UserPojo.class);

    summaryPojo。setUserPojo(userPojo);

    }