类中嵌套子类如何JSON转换

时间:2022-10-29 13:29:19

在开发中会经常遇到一个Java类中嵌套List集合,集合中又是另外一个类,那么在Json转换的时候可能会遇到无法转换,下面这个方法就可以完美解决

public class IM_UserAccount extends IM_BaseBean {
List<IM_UserAccount_Entity> entities;
String path;

public IM_UserAccount() {
super();
}

public List<IM_UserAccount_Entity> getEntities() {
return entities;
}

public void setEntities(List<IM_UserAccount_Entity> entities) {
this.entities = entities;
}

public String getPath() {
return path;
}

public void setPath(String path) {
this.path = path;
}
}
public class IM_UserAccount_Entity {
boolean activated;
long created;
long modified;
String type;
String username;
String uuid;

public IM_UserAccount_Entity() {
}

public boolean isActivated() {
return activated;
}

public void setActivated(boolean activated) {
this.activated = activated;
}

public long getCreated() {
return created;
}

public void setCreated(long created) {
this.created = created;
}

public long getModified() {
return modified;
}

public void setModified(long modified) {
this.modified = modified;
}

public String getType() {
return type;
}

public void setType(String type) {
this.type = type;
}

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public String getUuid() {
return uuid;
}

public void setUuid(String uuid) {
this.uuid = uuid;
}
}
   JSONObject jsonObject = JSONObject.fromObject(json);
Object o = JSONObject.toBean(jsonObject, IM_UserAccount.class, classMap);
<!-- 这里的classMap 是一个你内部数据对应的Java类 例如像本例中:-->
HashMap<String, Class> classHashMap = new HashMap<>();
classHashMap.put("entities", IM_UserAccount_Entity.class);

这个图片中的方法也行,不过目前本人还没有测试
类中嵌套子类如何JSON转换


JSONObject的maven坐标

   <dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>