java对象转换为json字符串

public static void main(String args[]){
		JSONObject jsonObject;
		JSONArray jsonArray;
		//数组转化为json
		String[] tempArry=new String[]{"a","b","c"};
		jsonArray=JSONArray.fromObject(tempArry);
		System.out.println(jsonArray.toString());//打印出来的结果:["a","b","c"]
		
		//list转换为json
		List<String> tempList=new ArrayList<String>();
		tempList.add("a");
		tempList.add("b");
		tempList.add("c");
		JSONArray	listJsonArray = JSONArray.fromObject(tempList);
		System.out.println(listJsonArray.toString());//打印出来的结果:["a","b","c"]
		
		//List 里面有对象
		List<User> objectList=new ArrayList<User>();
		User bean =new User();
		bean.setUserId("id1");
		bean.setUserName("name1");
		objectList.add(bean);
		bean =new User();
		bean.setUserId("id2");
		bean.setUserName("name2");
		objectList.add(bean);
		JSONArray json = JSONArray.fromObject(objectList); 
		System.out.println(json.toString());//打印结果:[{"userId":"id1","userName":"name1"},{"userId":"id2","userName":"name2"}]
		
		//对象转换为json
		User bean2 =new User();
		bean2.setUserId("id1");
		bean2.setUserName("name1");
		jsonObject = JSONObject.fromObject(bean2);
		System.out.println(jsonObject.toString());//打印结果:{"userId":"id1","userName":"name1"}
		
		//Map 转换为json
		Map<String,String> map= new HashMap<String,String>();
		map.put("key1", "value1");
		map.put("key2", "value2");
		jsonObject = JSONObject.fromObject(map);
		System.out.println(jsonObject);//打印结果:{"key2":"value2","key1":"value1"}
		
		//map里面有list
		Map<String,List> listMap= new HashMap<String,List>();
		List<User> mapList=new ArrayList<User>();
		User bean1 =new User();
		bean1.setUserId("id1");
		bean1.setUserName("name1");
		mapList.add(bean);
		listMap.put("key1", mapList);
		bean1 =new User();
		bean1.setUserId("id2");
		bean1.setUserName("name2");
		mapList.add(bean);
		listMap.put("key1", mapList);
		jsonObject = JSONObject.fromObject(listMap);
		System.out.println(jsonObject.toString());//打印结果:{"key1":[{"userId":"id1","userName":"name1"},{"userId":"id2","userName":"name2"}]}
	}

 

json解析的对象主要有2个JSONArray 和JSONObject

JSONArray 主要转换Object[] 和Collection

JSONObject主要解析对象和Map

 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值