JSONArray类将JavaBean,List,Map转换成json字符串

前端之家收集整理的这篇文章主要介绍了JSONArray类将JavaBean,List,Map转换成json字符串前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

Jar包



package cn.itcast.javaee.lucene.bean2json;

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

import org.junit.Test;

import net.sf.json.JSONArray;

/**
 * 第三方工具类,将JavaBean,List,Map转换成JSON文本
 * @author xuhaixing
 *
 */
public class TestJson {
	
	@Test
	public void javabean2json(){
		User user = new User(1,"哈哈",7000);
		JSONArray jsonArray = JSONArray.fromObject(user);
		String jsonJAVA = jsonArray.toString();
		System.out.println(jsonJAVA);
		//[{"id":1,"name":"哈哈","sal":7000}]
	}
	@Test
	public void list2json(){
		List<User> userList = new ArrayList<User>();
		userList.add(new User(1,"张三",1000));
		userList.add(new User(2,"李四",2000));
		userList.add(new User(3,"王五",3000));
		JSONArray jsonArray = JSONArray.fromObject(userList);
		String jsonJAVA = jsonArray.toString();
		System.out.println(jsonJAVA);
		//[{"id":1,"name":"张三","sal":1000},{"id":2,"name":"李四","sal":2000},{"id":3,"name":"王五","sal":3000}]
		
	}
	@Test
	public void map2json(){
		List<User> userList = new ArrayList<User>();
		userList.add(new User(1,"张三老婆","张三孩子",3000));
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("total",userList.size());
		map.put("rows",userList);
		
		JSONArray jsonArray = JSONArray.fromObject(map);
		String jsonJAVA = jsonArray.toString();
		System.out.println(jsonJAVA);
		//[{"total":3,"rows":[{"id":1,"name":"张三老婆","name":"张三孩子","sal":3000}]}]
		jsonJAVA = jsonJAVA.substring(1,jsonJAVA.length()-1);
		System.out.println(jsonJAVA);
		//{"total":3,"sal":3000}]}
	}
	
}	

猜你在找的Json相关文章