Java User 对象 JSON 解析错误:JSONArray 转换为 JSONObject 失败
{"title":"Java User 对象 JSON 解析错误:JSONArray 转换为 JSONObject 失败","description":"本文介绍了在使用 FastJSON 解析 JSON 字符串时,由于将 JSONArray 对象强制转换为 JSONObject 对象而导致的 ClassCastException 异常,并提供了解决方案。","keywords":"Java, JSON, FastJSON, JSONArray, JSONObject, ClassCastException, 解析错误, 解决方法","content":"public class User { private Integer id; private String name; private String address; private Date birth;
public User() {
}
public User(Integer id, String name, String address, Date birth) {
this.id = id;
this.name = name;
this.address = address;
this.birth = birth;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
@Override
public String toString() {
return "User{"
+ "id="
+ id
+ ", name='"
+ name
+ '', address='"
+ address
+ '', birth="
+ birth
+ '}';
}
} String json="[{"address":"广州","birth":1691063608890,"id":101,"name":"黄某"},{"address":"广州","birth":1691063608890,"id":102,"name":"黄某"},{"address":"广州","birth":1691063608890,"id":103,"name":"黄某"},{"address":"广州","birth":1691063608890,"id":104,"name":"黄某"},{"address":"广州","birth":1691063608890,"id":105,"name":"黄某"}]"; JSONObject parse= (JSONObject) JSON.parse(json); System.out.println(json); System.out.println(parse.get("id")); System.out.println(parse.get("name")); System.out.println(parse.get("address")); System.out.println(parse.get("birth")); User user=JSON.parseObject(json,User.class); System.out.println(user); /*Exception in thread "main" java.lang.ClassCastException: com.alibaba.fastjson.JSONArray cannot be cast to com.alibaba.fastjson.JSONObject at COPY.配置文件.test12.main(test12.java:40) 什么原因导致内容:这个错误是由于将JSONArray对象强制转换为JSONObject对象引起的。在给定的JSON字符串中,方括号"[]"表示一个JSONArray,而不是单个的JSONObject。因此,需要使用JSONArray来解析JSON字符串,而不是JSONObject。
你可以尝试以下代码来解决这个问题:
String json = "[{"address":"广州","birth":1691063608890,"id":101,"name":"黄某"},{"address":"广州","birth":1691063608890,"id":102,"name":"黄某"},{"address":"广州","birth":1691063608890,"id":103,"name":"黄某"},{"address":"广州","birth":1691063608890,"id":104,"name":"黄某"},{"address":"广州","birth":1691063608890,"id":105,"name":"黄某"}]";
JSONArray jsonArray = JSON.parseArray(json);
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
User user = JSON.parseObject(jsonObject.toJSONString(), User.class);
System.out.println(user);
}
这段代码将JSON字符串解析为一个JSONArray对象,然后遍历JSONArray并将每个JSONObject转换为User对象。最后,打印每个User对象的信息。
"
原文地址: https://www.cveoy.top/t/topic/qaFH 著作权归作者所有。请勿转载和采集!