【问题标题】:No serializer found for class org.json.JSONObject and no properties discovered to create BeanSerializer没有找到类 org.json.JSONObject 的序列化程序,也没有找到创建 BeanSerializer 的属性
【发布时间】:2014-11-21 14:18:11
【问题描述】:

从 Web 服务获取 JSON,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)

【问题讨论】:

    标签: java json spring rest serialization


    【解决方案1】:

    必须先将其作为 Json Array 接受,然后在读取其 Object 时必须使用 Object Mapper.readValue ,因为 Json Object 仍在 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);
    }
    

    【讨论】:

      猜你喜欢
      • 2021-06-26
      • 2020-04-22
      • 2017-05-27
      • 2012-10-25
      • 2018-02-05
      • 1970-01-01
      • 1970-01-01
      • 2016-02-17
      • 1970-01-01
      相关资源
      最近更新 更多