JSON详细学习之JackSon in JAVA

 需要依赖的jar包: jackson-annotations-2.2.1.jar  jackson-core-2.2.1.jar  jackson-core-asl-1.8.8.jar  jackson-databind-2.2.1.jar  jackson-mapper-asl-1.8.8.jar 


同样的,我们首先看一下JackSon对Json字符串的创建以及解析


       /**
	 * Map 转换为 json
	 */
	public static void MyTest01() {
		Map<String, String> hashMap = new HashMap<String, String>();
		hashMap.put("name", "zhang");
		hashMap.put("sex", "1");
		hashMap.put("login", "Jack");
		hashMap.put("password", "123abc");

		try {
			ObjectMapper objectMapper = new ObjectMapper();
			String userMapJson = objectMapper.writeValueAsString(hashMap);

			JsonNode node = objectMapper.readTree(userMapJson);

			// 输出结果转意,输出正确的信息
			System.out.println(node.get("password").asText());
			// 输出不转意,输出结果会包含"",这是不正确的,除非作为json传递,如果是输出结果值,必须如上一行的操作
			System.out.println(node.get("name"));
		} catch (IOException e) {
		}
	}

<span style="white-space:pre">	</span>/**
	 * 解析 json 格式字符串
	 */
	public static void MyTest03() {
		try {
			String str = "{\"data\":{\"birth_day\":7,\"birth_month\":6},\"errcode\":0,\"msg\":\"ok\",\"ret\":0}";

			ObjectMapper mapper = new ObjectMapper();
			JsonNode root = mapper.readTree(str);

			JsonNode data = root.path("data");

			JsonNode birth_day = data.path("birth_day");
			System.out.println(birth_day.asInt());

			JsonNode birth_month = data.path("birth_month");
			System.out.println(birth_month.asInt());

			JsonNode msg = root.path("msg");
			System.out.println(msg.textValue());
		} catch (IOException e) {
		}
	}

<span style="white-space:pre">	</span>/**
	 * json 直接提取 值
	 */
	public static void MyTest05() {
		try {
			// 演示字符串
			String str = "{\"data\":{\"hasnext\":0,\"info\":[{\"id\":\"288206077664983\",\"timestamp\":1371052476},{\"id\":\"186983078111768\",\"timestamp\":1370944068},{\"id\":\"297031120529307\",\"timestamp\":1370751789},{\"id\":\"273831022294863\",\"timestamp\":1369994812}],\"timestamp\":1374562897,\"totalnum\":422},\"errcode\":0,\"msg\":\"ok\",\"ret\":0,\"seqid\":5903702688915195270}";

			ObjectMapper mapper = new ObjectMapper();
			JsonNode root = mapper.readTree(str);

			// 提取 data
			JsonNode data = root.path("data");
			// 提取 info
			JsonNode info = data.path("info");

			System.out.println(info.size());

			// 得到 info 的第 0 个
			JsonNode item = info.get(0);
			System.out.println(item.get("id"));
			System.out.println(item.get("timestamp"));

			// 得到 info 的第 2 个
			item = info.get(2);
			System.out.println(item.get("id"));
			System.out.println(item.get("timestamp"));

			// 遍历 info 内的 array
			if (info.isArray()) {
				for (JsonNode objNode : info) {
					System.out.println(objNode);
				}
			}

		} catch (Exception e) {

		}
	}

<span style="white-space:pre">	</span>/**
	 * 创建一个 json,并向该 json 添加内容
	 */
	public static void MyTest07() {
		try {
			ObjectMapper mapper = new ObjectMapper();
			ObjectNode root1 = mapper.createObjectNode();

			root1.put("nodekey1", 1);
			root1.put("nodekey2", 2);

			System.out.println(root1.toString());

			// Create the root node
			ObjectNode root = mapper.createObjectNode();
			// Create a child node
			ObjectNode node1 = mapper.createObjectNode();
			node1.put("nodekey1", 1);
			node1.put("nodekey2", 2);
			// Bind the child nodes
			root.put("child", node1);
			// Array of nodes
			ArrayNode arrayNode = mapper.createArrayNode();
			arrayNode.add(node1);
			arrayNode.add(1);
			// Bind array node
			root.put("arraynode", arrayNode);

			System.out.println(mapper.writeValueAsString(root));
			// 得到的输出信息
			// {"child":{"nodekey1":1,"nodekey2":2},"arraynode":[{"nodekey1":1,"nodekey2":2},1]}
		} catch (Exception e) {

		}
	}
<span style="white-space:pre">	</span>// 创建一个 array node  
	public static void MyTest09() {
		try {
			ObjectMapper mapper = new ObjectMapper();
			ArrayNode arrayNode = mapper.createArrayNode();

			int i = 0;
			// 在 array 内创建 3 组 node 存入 array
			for (i = 0; i < 3; i++) {
				// 创建一个 node
				ObjectNode node = mapper.createObjectNode();

				node.put("nodeA", i);
				node.put("nodeB", i);
				node.put("nodeC", i);

				// 向 array 内添 node
				arrayNode.add(node);
			}

			// 根
			ObjectNode root = mapper.createObjectNode();
			root.put("total", i);
			root.put("rows", arrayNode);

			System.out.println(mapper.writeValueAsString(root));
			// 得到的输出信息
			// {"total":3,"rows":[{"nodeA":0,"nodeB":0,"nodeC":0},{"nodeA":1,"nodeB":1,"nodeC":1},{"nodeA":2,"nodeB":2,"nodeC":2}]}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

在添加 array 节点时,put node 的方法已经过时,将使用 set 方法 添加 array 节点,举例:

root.set ("rows", arrayNode);


由于我们涉及更多的是对象(Bean)与Json字符串之间的转换.这里我使用了前面介绍JSONObject的时候的model,实现同样的功能

package com.peter.jackson.test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.codehaus.jackson.map.ObjectMapper;
import com.peter.model.ClassInfo;
import com.peter.model.Student;
import com.peter.model.Teacher;

public class Test {
	public static void main(String[] args) {
		ObjectMapper objectMapper = new ObjectMapper();

		Student student1 = new Student();
		student1.setId(1);
		student1.setName("李坤");
		student1.setBirthDay(new Date());

		// //
		System.out.println("----------简单对象之间的转化-------------");
		// 简单的bean转为json
		String s1;
		try {
			
			//可以设置日期格式,默认格式为1445154660679
			//objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"));
			s1 = objectMapper.writeValueAsString(student1);
			System.out.println("简单Bean转化为Json===" + s1);
			System.out.println("简单Bean转化为Json==="+objectMapper.defaultPrettyPrintingWriter().writeValueAsString(student1));  
		// json转为简单Bean
			Student student = objectMapper.readValue(s1,Student.class);
			System.out.println("Json转为简单Bean===" + student);
		// //
//		
	        Student student2 = new Student();  
	        student2.setId(2);  
	        student2.setName("曹贵生");  
	        student2.setBirthDay(new Date());  
	  
	        Student student3 = new Student();  
	        student3.setId(3);  
	        student3.setName("柳波");  
	        student3.setBirthDay(new Date());  
	  
	        List<Student> list = new ArrayList<Student>();  
	        list.add(student1);  
	        list.add(student2);  
	        list.add(student3);  
	        System.out.println("----------带泛型的List之间的转化-------------"); 
//        // 带泛型的list转化为json  
	        String s2 = objectMapper.writeValueAsString(list);
	        System.out.println("带泛型的list转化为json==" + s2);
//        // json转为带泛型的list   List<Student> retList = objectMapper.readValue(s2, List.class);沒办法转
	        //可以用Arrays.asList将其转换成List即可
	        Student[] stus = objectMapper.readValue(s2, Student[].class);
	        for (Student stu : stus) {  
	            System.out.println(stu);  
	        }  
//	        List<Student> retList = Arrays.asList(stus);
//	        for (Student stu : retList) {  
//	            System.out.println(stu);  
//	        }  
	        
	        System.out.println("----------json字符串转换成List<Map>集合-------------"); 
	        List<LinkedHashMap<String, Object>> list1 = objectMapper.readValue(s2, List.class);
	        for (int i = 0; i < list1.size(); i++) {
	            Map<String, Object> map = list1.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));
	            }
	        }
	        
	        Teacher t = new Teacher();
	        t.setJabNum("t101");
	        t.setName("lijun");
	        ClassInfo ci = new ClassInfo();
	        ci.setClassName("cna");
	        ci.setClassNum(101);
	        ci.setStudents(list);
	        ci.setTeacher(t);
	        String c = objectMapper.writeValueAsString(ci);
	        System.out.println("ci to json  //");
	        System.out.println(c);
	        System.out.println("json to ci //");
	        ClassInfo cijson = objectMapper.readValue(c, ClassInfo.class);
	        System.out.println(cijson);
	        
	        System.out.println(" Json字符串转换成Map集合 //");
	        String json = "{\"success\":true,\"A\":{\"address\": \"address2\",\"name\":\"haha2\",\"id\":2,\"email\":\"email2\"},"+
	                "\"B\":{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}}";
	        Map<String, Map<String, Object>> maps = objectMapper.readValue(json, Map.class);
	        System.out.println(maps.size());
	        Set<String> key = maps.keySet();
	        Iterator<String> iter = key.iterator();
	        while (iter.hasNext()) {
	            String field = iter.next();
	            System.out.println(field + ":" + maps.get(field));
	        }
		} catch (IOException e) {
			e.printStackTrace();
		}

     
	}
}
具体结果与上一篇的JsonObject一致,请自主运行测试.

参考文章:http://blog.csdn.net/joyous/article/details/9448461

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值