java 对象转json字符串方法_jackson使用

下面介绍一下使用jackson jar把对象转成json字符串的方法,

有属性,有list集合

使用jackson的jar包有jackson-annotations-2.2.0.jar,jackson-core-2.2.0.jar,jackson-databind-2.2.0.jar

代码实例如下:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import com.fasterxml.jackson.databind.ObjectMapper;


public class ObjectToJson {

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception{
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		
		List<Map<String, String>> userList = new ArrayList<Map<String,String>>();
		Map<String, String> userMap = new HashMap<String, String>();
		userMap.put("userId", "1212");
		userMap.put("userName", "test");
		userList.add(userMap);
		Map<String, String> userMap2 = new HashMap<String, String>();
		userMap2.put("userId", "2222");
		userMap2.put("userName", "test2");
		userList.add(userMap2);
		
		jsonMap.put("userList", userList);
		ObjectMapper mapper = new ObjectMapper();
		
		String jsonStr = mapper.writeValueAsString(jsonMap);
		System.out.println(jsonStr);
	}

}

运行结果:{"userList":[{"userId":"1212","userName":"test"},{"userId":"2222","userName":"test2"}]}

来源://作者:/更新时间:2015-06-17
相关文章
评论:
验证码:
匿名评论: