当前位置: 首页 > 面试题库 >

找不到针对类org.json.JSONObject的序列化器,也未发现创建BeanSerializer的属性

谭铭
2023-03-14
问题内容

从Web服务获取Json Array的JSON作为响应

   [3]
   0:  {
   id: 2
  name: "a561137"
    password: "test"
  firstName: "abhishek"
   lastName: "ringsia"
    organization: "bbb"
      }-
    1:  {
      id: 3
  name: "a561023"
password: "hello"
     firstName: "hello"
   lastName: "hello"
     organization: "hello"
   }-
 2:  {
  id: 4
  name: "a541234"
  password: "hello"
 firstName: "hello"
  lastName: "hello"
  organization: "hello"
    }

在JsonArray中获取响应后,在读取Json Array的Json对象时出现错误:

List<User> list = new ArrayList<User>();
JSONArray jsonArr = new JSONArray(response);

for (int i = 0; i < jsonArr.length(); i++) {
    JSONObject jsonObj = jsonArr.getJSONObject(i);
    ObjectMapper mapper = new ObjectMapper();
    User usr=   mapper.convertValue(jsonObj, User.class);
    list.add(usr);
}

找不到针对类org.json.JSONObject的序列化程序,也没有发现创建BeanSerializer的属性(为避免异常,请禁用SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS))


问题答案:

必须首先将其作为Json数组接受,然后在读取其Object时必须使用Object Mapper.readValue,因为Json Object Still
in String。

List<User> list = new ArrayList<User>();
JSONArray jsonArr = new JSONArray(response);

for (int i = 0; i < jsonArr.length(); i++) {
    JSONObject jsonObj = jsonArr.getJSONObject(i);
    ObjectMapper mapper = new ObjectMapper();
    User usr = mapper.readValue(jsonObj.toString(), User.class);      
    list.add(usr);
}


 类似资料: