我正在尝试使用List<Object>
将JSON
转换为ObjectMapper
格式。我试过下面但是我得到了例外,即
com.fasterxml.jackson.databind.exc.MismatchedInputException:
public List<ClientRT> callSP() throws IOException {
List<Object> crt=crtRepo.roomtype(60);
ObjectMapper mapper = new ObjectMapper();
String json=mapper.writeValueAsString(crt);
//ClientRT obj=mapper.readValue(json,ClientRT.class);
List<ClientRT> obj=mapper.readValue(json,mapper.getTypeFactory()
.constructCollectionLikeType(List.class,ClientRT.class));
return obj;
}
ClientRT类
public class ClientRT {
public Integer res_nclient_room_type_id;
public String res_sclient_rt_desc;
public String res_sclient_rt_name;
public String res_sclient_rt_code;
//getter setter
public ClientRT() {
super();
}
@Override
public String toString() {
return "ClientRT [res_nclient_room_type_id=" + res_nclient_room_type_id + ", res_sclient_rt_desc="
+ res_sclient_rt_desc + ", res_sclient_rt_name=" + res_sclient_rt_name + ", res_sclient_rt_code="
+ res_sclient_rt_code + "]";
}
}
在JSON中期待结果
[
{ "res_nclient_room_type_id":1 ,
"res_sclient_rt_desc": "FACILITIES - AVAILABLE ROOM",
"res_sclient_rt_name":"FACILITIES - AVAILABLE ROOM" ,
"res_sclient_rt_code":"050"
},
]
例外
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `com.spacestudy.model.ClientRT` out of START_ARRAY token
at [Source: (String)"[[1,"TEMPORARILY NOT ASSIGNED","TEMPORARILY NOT ASSIGNED","000"],[2,"FACILITIES - AVAILABLE ROOM","FACILITIES - AVAILABLE ROOM","050"],[3,"FACILITIES - UNDEFINED PURPOSE","FACILITIES - UNDEFINED PURPOSE","060"],[4,"FACILITIES - UNFINISHED AREA","FACILITIES - UNFINISHED AREA","070"],[5,"CLASSROOM/LECTURE HALL","CLASSROOM/LECTURE HALL","110"],[6,"CLASSROOM SERVICE","CLASSROOM SERVICE","115"],[7,"CLASSROOM STORAGE","CLASSROOM STORAGE","116"],[8,"CLASSROOM KITCHEN","CLASSROOM KITCHEN","119"],[9,"CLA"[truncated 8500 chars]; line: 1, column: 2] (through reference chain: java.util.ArrayList[0])
任何人都可以告诉我如何解决这个例外情况?
正如上面的amicoderozer所提到的,你需要从json而不是类中删除类ClientRT
的字段的数据类型。
你传给杰克逊的json是不正确的。
而不是传给杰克逊这个Json:
[
{ "res_nclient_room_type_id":1 ,
"public String res_sclient_rt_desc": "FACILITIES - AVAILABLE ROOM",
"public String res_sclient_rt_name":"FACILITIES - AVAILABLE ROOM" ,
"public String res_sclient_rt_code":"050"
}
]
试试这个(从json中删除public String
):
[
{ "res_nclient_room_type_id":1 ,
"res_sclient_rt_desc": "FACILITIES - AVAILABLE ROOM",
"res_sclient_rt_name":"FACILITIES - AVAILABLE ROOM" ,
"res_sclient_rt_code":"050"
}
]
杰克逊无法解析json,因为它无法在类ClientRT
中找到相应的Java字段。从json中删除public String
,只留下ClientRT
类字段的名称。