Java对象与json对象的转行

本文介绍了一个实用工具包jsontools,它可以轻松实现Java对象与JSON字符串之间的相互转换。通过具体的代码示例,展示了如何利用该工具包进行序列化与反序列化操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
// }
//
// }
// );

}
}


需要:jsontools-core-1.7 和 antlrworks-1.3.1.jar (附件)
转自:http://www.iteye.com/topic/647308
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值