【问题标题】:want to deserialize json string into java object with arraylist想用arraylist将json字符串反序列化为java对象
【发布时间】:2015-08-17 06:11:50
【问题描述】:

java 对象:MyObject 有AnotherObject1 的列表,AnotherObject1 也有AnotherObject2 的列表

class MyObject{

private String                  status;

private String                  message;

private List<AnotherObject1>            data;
public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public List<AnotherObject1> getData() {
        return data;
    }

    public void setData(List<AnotherObject1> data) {
        this.data = data;
        }
}

Class AnotherObject1{
private Integer                 group_id;

 private List<AnotherObject2>           anotherList;
public Integer getGroup_id() {
   return group_id;
}

public void setGroup_id(Integer group_id) {
   this.group_id = group_id;
}

public List<AnotherObject2> getAnotherList() {
  return smsList;
}

public void setAnotherList(List<AnotherObject2> anotherList) {
   this.anotherList = anotherList;
}

}

class AnotherObject2{
  private String                    customid;

    private String                  customid1   ;

    private Long                    mobile;

    private String                  status;

    private String                  country;

    public String getCustomid() {
        return customid;
    }

    public void setCustomid(String customid) {
        this.customid = customid;
    }

    public String getCustomid1() {
        return customid1;
    }

    public void setCustomid1(String customid1) {
        this.customid1 = customid1;
    }

    public Long getMobile() {
        return mobile;
    }

    public void setMobile(Long mobile) {
        this.mobile = mobile;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }


}

JSON 字符串:这是我的 json 字符串,我想通过它使用对象映射器制作一个 java 对象

String response="{\"status\":\"OK\",\"data\":{\"group_id\":39545922,\"0\":{\"id\":\"39545922-1\",\"customid\":\"\",\"customid1\":\"\",\"customid2\":\"\",\"mobile\":\"910123456789\",\"status\":\"XYZ\",\"country\":\"IN\"}},\"message\":\"WE R Happy.\"}"

ObjectMapper 代码 //将字符串转换为响应对象

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
objectMapper.readValue(responseBody, MyObject.class);

异常:这里是异常

com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token
 at [Source: {"status":"OK","data":{"group_id":39545922,"0":{"id":"39545922-1","customid":"","customid1":"","customid2":"","mobile":"910123456789","status":"GOOD","country":"IN"}},"message":"We R happy."}; line: 1, column: 15] (through reference chain: MyObject["data"])
    at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:148)
    at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:854)
    at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:850)
    at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.handleNonArray(CollectionDeserializer.java:292)
    at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:227)
    at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:217)
    at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:25)
    at com.fasterxml.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:520)
    at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:95)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:256)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:125)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3702)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2714)
    at abc.disp(RestClientImpl.java:210)
    at abc.disp(RestClientImpl.java:105)
    at Application.<init>(Application.java:42)
    at Application.main(Application.java:45)

请指导我如何使它成为可能。

【问题讨论】:

  • 好吧,我对 JSON 不是很熟悉,但我可以想象在尝试反序列化 AnotherObject1 的实例时,"group_id" : ..., "0" : { ... } 部分中的 0 是一个问题。实例字段未命名为0,而是命名为smsList
  • @Seelenvirtuose 是正确的。这不是有效的 JSON 字符串。此外,JSON 字符串不包含任何 [] 列表

标签: java json jackson deserialization


【解决方案1】:

您的代码本身不可编译...

private List<AnotherObject1> data; // Your class member is list of AnotherObject1

在getter和setter中用作SMSDTO列表

public List<SMSDTO> getData() {
    return data;
}

【讨论】:

    【解决方案2】:

    问题很简单:你声称data 应该变成Java List;这要求它的 JSON 输入应该是 JSON 数组。但是 JSON 拥有的是 JSON 对象。

    所以您要么需要更改 POJO 定义以期望与 JSON 对象兼容的东西(POJO 或java.util.Map);或 JSON 以包含 data 的数组。

    【讨论】:

      【解决方案3】:

      首先,正如 Naveen Ramawat 所说,您的代码不能按原样编译。

      • 在 AnotherObject1 类中,getSmsList 应采用 AnotherObject2,setSmsList 也应采用 AnotherObject2 作为参数。
      • 在 MyObject 类中,setData 和 getData 应使用 AnotherObject1 作为参数

      第二个你的 JSON 字符串无效,它应该是这样的:

      {"status":"OK","data":[{"group_id":39545922,"smsList":[{"customid":"39545922-1","customid1":"","mobile":913456789,"status":"XYZ","country":"XYZ"}]}]}
      

      这是我使用的代码:

      MyObject.java:

          import java.util.List;
      
          class MyObject {
      
              private String status;
      
              private String message;
      
              private List<AnotherObject1> data;
      
              public String getStatus() {
                  return status;
              }
      
              public void setStatus(String status) {
                  this.status = status;
              }
      
              public String getMessage() {
                  return message;
              }
      
              public void setMessage(String message) {
                  this.message = message;
              }
      
              public List<AnotherObject1> getData() {
                  return data;
              }
      
              public void setData(List<AnotherObject1> data) {
                  this.data = data;
              }
          }
      

      另一个Object1.java:

          import java.util.List;
      
          public class AnotherObject1 {
              private Integer group_id;
      
              private List<AnotherObject2> smsList;
      
              public Integer getGroup_id() {
                  return group_id;
              }
      
              public void setGroup_id(Integer group_id) {
                  this.group_id = group_id;
              }
      
              public List<AnotherObject2> getSmsList() {
                  return smsList;
              }
      
              public void setSmsList(List<AnotherObject2> smsList) {
                  this.smsList = smsList;
              }
          }
      

      另一个Object2.java:

          public class AnotherObject2 {
      
              private String customid;
      
              private String customid1;
      
              private Long mobile;
      
              private String status;
      
              private String country;
      
              public String getCustomid() {
                  return customid;
              }
      
              public void setCustomid(String customid) {
                  this.customid = customid;
              }
      
              public String getCustomid1() {
                  return customid1;
              }
      
              public void setCustomid1(String customid1) {
                  this.customid1 = customid1;
              }
      
              public Long getMobile() {
                  return mobile;
              }
      
              public void setMobile(Long mobile) {
                  this.mobile = mobile;
              }
      
              public String getStatus() {
                  return status;
              }
      
              public void setStatus(String status) {
                  this.status = status;
              }
      
              public String getCountry() {
                  return country;
              }
      
              public void setCountry(String country) {
                  this.country = country;
              }
      
          }
      

      获取 JSON 字符串:

          import org.json.JSONObject;
          import org.json.XML;
      
          import com.google.gson.Gson;
      
          MyObject myObj = new MyObject();
          ArrayList<AnotherObject2> smsList = new ArrayList<AnotherObject2>();
          ArrayList<AnotherObject1> data = new ArrayList<AnotherObject1>();
          AnotherObject1 ao1 = new AnotherObject1();
          ao1.setGroup_id(39545922);
          ao1.setSmsList(smsList);
          AnotherObject2 sms = new AnotherObject2();
          sms.setCountry("XYZ");
          sms.setCustomid("39545922-1");
          sms.setCustomid1("");
          sms.setMobile((long) 913456789);
          sms.setStatus("XYZ");
          smsList.add(sms);
          ao1.setSmsList(smsList);
          data.add(ao1);
          myObj.setStatus("OK");
          myObj.setData(data);
          // Build a JSON string to display
          Gson gson = new Gson();
          String jsonString = gson.toJson(myObj);
          System.out.println(jsonString);
          // Get an object from a JSON string
          MyObject myObject2 = gson.fromJson(jsonString, MyObject.class);
          // Display the new object
          System.out.println(gson.toJson(myObject2));
      

      【讨论】:

      • 是的,我必须解析它...我想使用对象映射器将 json 字符串转换为 java 对象
      • 在我使用的代码示例的末尾,您可以找到从 json 字符串到 java 对象的转换。为此,我使用了谷歌 gson: com.google.code.gsongson2.3.1
      猜你喜欢
      • 2020-02-03
      • 1970-01-01
      • 1970-01-01
      • 2022-01-20
      • 1970-01-01
      • 2014-01-04
      • 1970-01-01
      • 2012-04-24
      • 1970-01-01
      相关资源
      最近更新 更多