关闭

jacksonUtil

1939人阅读 评论(0) 收藏 举报
分类:
jackson对json的转换
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonUtil {
		
	public static String mapToJon(Object object) throws JsonProcessingException
	{
		ObjectMapper mapper = new ObjectMapper();
		return mapper.writeValueAsString(object);
	}
	
	public static String ListToJon(List list) throws JsonProcessingException
	{
		ObjectMapper mapper = new ObjectMapper();
		return mapper.writeValueAsString(list);
	}
	
	public static String objectToJson(Object object)throws JsonProcessingException
	{
		ObjectMapper mapper = new ObjectMapper();
		return mapper.writeValueAsString(object);
	}
	
		public static void main(String args[]) throws Exception, JsonMappingException, IOException
		{
			ObjectMapper mapper = new ObjectMapper();
	//		Map<String,Object> userData = mapper.readValue(new File("user.json"), Map.class);
		
			
		/*  将java对象装换成json数据*/
		/*	User u=new User();
			u.setAge("23");
			u.setName("xx");
			u.getHobby().add("pingbing");
			u.getHobby().add("dd");
			u.getHobby().add("e");
			u.getPartner().put("Name", "ss");
			u.getPartner().put("Name1", "ss");
			u.getPartner().put("Name2", "ss");
			System.out.println(mapper.writeValueAsString(u));*/
			
		/*	将json装换成pojo
			String s="{\"name\":\"xx\",\"age\":\"23\",\"hobby\":[\"pingbing\",\"dd\",\"e\"],\"partner\":{\"Name\":\"ss\",\"Name2\":\"ss\",\"Name1\":\"ss\"}}";
			User user=mapper.readValue(s, User.class);
			System.out.println(user.getAge()+user.getHobby().toString()+user.getPartner().toString());*/
		
		/*	map 转换成json
			Map<String,Object> map=new HashMap<String,Object>();
			Map<String,Object> map2=new HashMap<String,Object>();
			map2.put("currentPage", "3");
			map2.put("size", "10");
			map2.put("total", "10");
			map.put("name","d");
			map.put("pageInfo", map2);
			System.out.println(mapper.writeValueAsString(map));*/

		/*	json 装换成map
			String s="{\"pageInfo\":{\"total\":\"10\",\"currentPage\":\"3\",\"size\":\"10\"},\"name\":\"d\"}";
			Map map=mapper.readValue(s,Map.class );
			Map map2=(Map) map.get("pageInfo");
			System.out.println(map2);*/
			
			Map<String,Object> map=new HashMap<String,Object>();
			Map<String,Object> map2=new HashMap<String,Object>();
			map2.put("currentPage", "3");
			map2.put("size", "10");
			map2.put("total", "10");
			map.put("name","d");
			List list=new ArrayList();
			list.add(map2);
			map.put("pageInfo", list);
			
			System.out.println(mapper.writeValueAsString(list));
		}
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:21121次
    • 积分:632
    • 等级:
    • 排名:千里之外
    • 原创:40篇
    • 转载:13篇
    • 译文:1篇
    • 评论:8条
    文章分类