json的几种相互转换

首先对json支持要导入两个jar包

 

 

先创建两个类

AccountBean.java

public class AccountBean {
	private int id;
	private String name;
	private String email;
	private String address;
	private Birthday birthday;
	//此处省略get和set和tostring方法
} 

Birthday.java

public class Birthday {
   private Date birthday;
   public Birthday(Date bDate){
       this.birthday=bDate;
   }

    public Date getBirthday()
    {
        return birthday;
    }
    
    public void setBirthday(Date birthday)
    {
        this.birthday = birthday;
    }
   
	
}

 

测试类:

 

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

@SuppressWarnings("unchecked")
public class JacksonTest {
	private JsonGenerator jsonGenerator = null;
	private ObjectMapper objectMapper = null;
	private AccountBean bean = null;

	@Before
	public void init() {
		bean = new AccountBean();
		bean.setAddress("china-Guangzhou");
		bean.setEmail("hoojo_@126.com");
		bean.setId(1);
		bean.setName("hoojo");
		bean.setBirthday(new Birthday(new Date()));

		objectMapper = new ObjectMapper();
		try {
		    
			jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(System.out, JsonEncoding.UTF8);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@After
	public void destory() {
		try {
			if (jsonGenerator != null) {
				jsonGenerator.flush();
			}
			if (!jsonGenerator.isClosed()) {
				jsonGenerator.close();
			}
			jsonGenerator = null;
			objectMapper = null;
			bean = null;
			System.gc();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * <b>function:</b>将java对象转换成json字符串
	 */
	@Test
	public void writeEntityJSON() {

		try {
		    System.out.println("--------------将java对象转换成json字符串---------------------");
			System.out.println("jsonGenerator");
			// writeObject可以转换java对象,eg:JavaBean/Map/List/Array等
			jsonGenerator.writeObject(bean);
			System.out.println();

			System.out.println("ObjectMapper");
			// writeValue具有和writeObject相同的功能
			objectMapper.writeValue(System.out, bean);
		    
		    		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * <b>function:</b>将map转换成json字符串
	 */
	@Test
	public void writeMapJSON() {
		try {
		    System.out.println("-----------将map转换成json字符串---------");
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("name", bean.getName());
			map.put("account", bean);
			bean = new AccountBean();
			bean.setAddress("china-Beijin");
			bean.setEmail("hoojo@qq.com");
			map.put("account2", bean);

			System.out.println("jsonGenerator");
			jsonGenerator.writeObject(map);
			System.out.println("");

			System.out.println("objectMapper");
			objectMapper.writeValue(System.out, map);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * <b>function:</b>将list集合转换成json字符串
	 */
	@Test
	public void writeListJSON() {
		try {
		    System.out.println("-------------将list集合转换成json字符串---------------");
			List<AccountBean> list = new ArrayList<AccountBean>();
			list.add(bean);

			bean = new AccountBean();
			bean.setId(2);
			bean.setAddress("address2");
			bean.setEmail("email2");
			bean.setName("haha2");
			list.add(bean);

			System.out.println("jsonGenerator");
			// list转换成JSON字符串
			jsonGenerator.writeObject(list);
			System.out.println();
			System.out.println("ObjectMapper");
			// 用objectMapper直接返回list转换成的JSON字符串
			System.out.println("1###" + objectMapper.writeValueAsString(list));
			System.out.print("2###");
			// objectMapper list转换成JSON字符串
			objectMapper.writeValue(System.out, list);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Test   //将json字符串转换成java对象
	public void readJson2Entity() {
		String json = "{\"address\":\"地址\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}";
		try {
			AccountBean acc = objectMapper.readValue(json, AccountBean.class);
			System.out.println(acc.getName());
			System.out.println(acc);
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * <b>function:</b>json字符串转换成list<map>
	 * 
	 */
	@Test
	public void readJson2List() {
		String json = "[{\"address\": \"address2\",\"name\":\"haha2\",\"id\":2,\"email\":\"email2\"},{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}]";
		try {
			List<LinkedHashMap<String, Object>> list = objectMapper.readValue(
					json, List.class);
			System.out.println(list.size());
			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));
				}
			}
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * <b>function:</b>json字符串转换成Array
	 * 
	 */
	@Test
	public void readJson2Array() {
		String json = "[{\"address\": \"address2\",\"name\":\"haha2\",\"id\":2,\"email\":\"email2\"},{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}]";
		try {
			AccountBean[] arr = objectMapper.readValue(json,
					AccountBean[].class);
			System.out.println(arr.length);
			for (int i = 0; i < arr.length; i++) {
				System.out.println(arr[i]);
			}

		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * <b>function:</b>json字符串转换成Array
	 * 
	 */
	@Test
	public void myReadJson2Array() {
		String json = "	[{\"goodsId\":\"10\",\"goodsName\":\"苹果4\"},{\"goodsId\":\"2\",\"goodsName\":\"note2\"}]";
		try {
			BuyOrderDetail[] arr = objectMapper.readValue(json, BuyOrderDetail[].class);
			System.out.println(arr.length);
			for (int i = 0; i < arr.length; i++) {
				System.out.println(arr[i]);
			}
			
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值