jsontools 工具包可以将Java对象转化成json对象,也可以讲jsonString 转化成Java对象,转化的过程十分方便。
注意:1.对象必需实现默认的构造函数,因为jsontools在解析的时候使用了反射实例化属性对象,
2.必需给属性提供get,set 方法,因为jsontools 使用了内省获得属性值。
public class Blog {
private Author writer;
private List<Entry> entries = new ArrayList<Entry> ();
public Blog() {
super();
}
public Blog(Author writer) {
this.writer = writer;
}
public void add(Entry entry) {
entries.add(entry);
}
public Author getWriter() {
return writer;
}
public void setWriter(Author writer) {
this.writer = writer;
}
public List<Entry> getEntries() {
return entries;
}
public void setEntries(List<Entry> entries) {
this.entries = entries;
}
}
public class Author {
private String name;
public Author() {
super();
}
public Author(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
public class Entry {
private String title, description;
public Entry() {
super();
}
public Entry(String title, String description) {
this.title = title;
this.description = description;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
public static void main(String[] args) throws Exception {
try {
Object o = Blog.class.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
Blog teamBlog = new Blog(new Author("Guilherme Silveira"));
teamBlog.add(new Entry("first", "My first blog entry."));
teamBlog
.add(new Entry("tutorial",
"Today we have developed a nice alias tutorial. Tell your friends! NOW!"));
// 序列化
JSONValue jsonValue = JSONMapper.toJSON(teamBlog);
String jsonStr = jsonValue.render(true); // 是否格式化
System.out.println(jsonStr);
// 反序列化
JSONParser parser = new JSONParser(new StringReader(jsonStr));
// JSONObject.decorate(anObject)
Blog b = (Blog) JSONMapper.toJava(parser.nextValue(), Blog.class);
System.out.println(b);
// Blog b = (Blog)JSONMapper.toJava(parser.nextValue(),
// new ParameterizedType(){
//
// @Override
// public Type[] getActualTypeArguments() {
//
// return null;
// }
//
// @Override
// public Type getOwnerType() {
//
// return null;
// }
//
// @Override
// public Type getRawType() {
//
// return null;
// }
//
// }
// );
}
}