日期:2014-05-16  浏览次数:20312 次

Jackson json基本应用
   Jackson可以轻松的将Java对象转换成json对象和xml文档,同样也可以将json、xml转换成Java对象。(xml需要添加额外stax2-api.jar)
   相比json-lib框架,Jackson所依赖的jar包较少,简单易用并且性能也要相对高些。而且Jackson社区相对比较活跃,更新速度也比较快。

1、 下载依赖库jar包
   官网:http://jackson.codehaus.org/
   下载最新jar:
    jackson-annotations-2.2.0.jar
    jackson-databind-2.2.0.jar
     jackson-core-2.2.0.jar

2、 基础类
public class Birthday {
   private String test;
   private String birthday;

}

public class User {
   Float number;
   String uname;
   String upwd;
   Integer uid;
   Birthday birthday;
}


/**
* 实体JSON间互相转换
*
* @throws IOException
*/
public static void writeEntity2Json() throws IOException {
User user = new User();
user.setUid(5);
user.setUname("tom");
user.setUpwd("123");
user.setNumber(3.44f);
Birthday b = new Birthday();
b.setBirthday("1900-11-11");
b.setTest("测试");
user.setBirthday(b);

objectMapper = new ObjectMapper();

String tt = objectMapper.writeValueAsString(user);
System.out.println("===" + tt);

User user2 = objectMapper.readValue(tt, User.class);
System.out.println("逆转==>" + user2.toString());

}



/**
* List json 间相互转换
*
* @throws IOException
* @throws JsonMappingException
* @throws JsonGenerationException
*/
public static void writeList2Json() throws IOException {
List<User> userList = new ArrayList<User>();

User user = new User();
user.setUid(5);
user.setUname("tom");
user.setUpwd("123");
user.setNumber(3.44f);
Birthday b = new Birthday();
b.setBirthday("1900-11-11");
b.setTest("测试");
user.setBirthday(b);

userList.add(user);

userList.add(user);

String tt = objectMapper.writeValueAsString(userList);
System.out.println("===" + tt);

List<LinkedHashMap<String, Object>> list = objectMapper.readValue(tt, List.class);

for (int i = 0; i < list.size(); i++) {
            Map<String, Object> map = list.get(i);
           
            Set<String> set = map.keySet();
            for (Iterator<String> it = set.iterator();it.hasNext();) {
                String key = it.next();
                System.out.println(key + ":" + map.get(key));
            }
        }

}