所使用的包:
commons-beanutils.jar
commons-collections-3.1.jar
commons-lang.jar
commons-logging-1.1.3.jar
ezmorph-1.0.jar
json-lib-2.2.2-jdk15.jar
先看json和String的互转
User.java user对象
package test;public class User {String id;String name;int age;//省略get set }
json.java
package test;import net.sf.json.JSONObject;public class Json{public static void main(String[] args) {//String 转jsonString text ="{'id':'001','name':'jack','age':22}";JSONObject jo =JSONObject.fromObject(text);System.out.println(jo.get("id") +"__"+ jo.get("name") +"___" + jo.getInt("age"));
//String 转对象 等于是先转成json然后转对象String text2="{'id':'002','name':'lion','age':23}";User u1 = (User)JSONObject.toBean(JSONObject.fromObject(text2), User.class);System.out.println(u1.getId()+"___"+u1.getName()+"__"+u1.getAge());
//对象转jsonUser u =new User();u.setId("003");u.setAge(25);u.setName("Tom");JSONObject jo2 =JSONObject.fromObject(u);System.out.println(jo2);System.out.println(jo2.get("name"));}}
打印输出
001__jack___22
002___lion__23
{"age":25,"id":"003","name":"Tom"}
Tom
给User.java 增加一个新属性book
package test;public class User {String id;String name;int age;Book book;// get set }
Book.java
package test;public class Book {String id;String name;//get set }
那么把user 转成json是什么样的呢?
package test;import net.sf.json.JSONObject;public class Json {public static void main(String[] args) {Book book =new Book();book .setId("111");book.setName("语文");User u =new User();u.setId("002");u.setName("xim");u.setBook(book);JSONObject jo =JSONObject.fromObject(u);System.out.println(jo);}}
输出打印
{"age":0,"book":{"id":"111","name":"语文"},"id":"002","name":"xim"}
互转方法与第一种相同。