我有一个JSON字符串,其中包含一个对象列表:
[
{title: title1,id: 1,children: [
{title: title1_1,id: 1_1,children: [
{title: title1_1_1,id: 1_1_1,children: []},
{title: title1_1_2,id: 1_1_2,children: []}
]}
]},
{title: title2,id: 2,children: [
{title: title2_1,id: 2_2,children: []}
]}
]
我想从上面的json字符串创建java中的Objects列表。
我可以使用Jackson包中的jsonMapper读取方法吗?
你能举一些例子吗?
- 编辑 -
这是我的班级。
@Entity
@Table(name="procedure__SkeletonElement")
@Inheritance(strategy=InheritanceType.JOINED)
@DiscriminatorColumn(name="type")
public abstract class SkeletonElement extends GenericHierarchicalModel<SkeletonElement> {
@Transient
public String getDecriminatorValue() {
return this.getClass().getSimpleName();
}
@Override
public String toJson() {
return "{\"title\":\"" + this.getName() + "\", \"id\":\"" + this.getId() + "\", \"type\":\"" + this.getDecriminatorValue() + "\", \"children\": [" + listToJson(this.getChildren()) + "]}";
}
public SkeletonElement toObject(String jsonObject) {
System.out.println("dedicated method");
ObjectMapper jsonMapper = new ObjectMapper();
try {
//GenericModel<T> t = jsonMapper.readValue(jsonObject, GenericModel.class);
SkeletonElement skeletonElement = jsonMapper.readValue(jsonObject, SkeletonElement.class);
//return t;
return skeletonElement;
} catch (JsonGenerationException e) {
e.printStackTrace();
return null;
} catch (JsonMappingException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
和扩展的类:
@MappedSuperclass
public abstract class GenericHierarchicalModel<T extends GenericHierarchicalModel<T>> extends GenericModel<T> {
private String name;
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private T parent;
@OneToMany(mappedBy = "parent")
private List<T> children;
public String getName() {return name;}
public void setName(String name) {this.name = name;}
public T getParent() {return parent;}
public void setParent(T parent) {this.parent = parent;}
public List<T> getChildren() {return children;}
public void setChildren(List<T> children) {this.children = children;}
@Override
public String toJson() {
return "{\"title\":\"" + this.name + "\", \"id\":\"" + this.getId() + "\", \"children\": [" + listToJson(this.getChildren()) + "]}";
}
public String listToJson(List<T> children) {
String json = "";
for(int i=0; i<children.size(); i++) {
json = json + children.get(i).toJson();
if(children.size()!=i+1) {
json = json + ", ";
}
}
return json;
}
}
发生当前错误:
org.codehaus.jackson.map.JsonMappingException: Can not construct instance of com.derp.procedure.model.SkeletonElement, problem: abstract types can only be instantiated with additional type information
at [Source: java.io.StringReader@6e927a3a; line: 1, column: 1]