Json格式转换,String,Array,List,Map

Json格式转换,String,Array,List,Map

net.sf.json.JSONObject 和org.json.JSONObject 的差别 net.sf.json.JSONObject 没有构造方法 org.json.JSONObject 有构造方法 org 在jdk1.5下不支持

package cn.itcast.caoke.json;

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

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class JsonTest {
	public static void main(String[] args) {
		
		Person person = new Person();
		person.setName("caokePerson");
		person.setAge(23);
		
		// 1.直接放json对象	
		// 直接new JSONObject 对象 ,像map一样赋值
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("name", "caoke");
		System.out.println("----直接放json对象----"+jsonObject.toString());
		
		// 2. 对象转换为json	
		//使用 JSONObject的静态对象方法,把对象直接转换为JSONObject
		jsonObject = JSONObject.fromObject(person);
		System.out.println("----对象转换为json----"+jsonObject.toString());
		
		// 3.集合转换json
		// 用JSONArray的静态方法把集合转换为JsonArray
		List<Person> persons = new ArrayList<Person>();
		Person person2 = new Person();
		person2.setName("caokePerson2");
		person2.setAge(23);
		persons.add(person);
		persons.add(person2);
		JSONArray jsonArray = JSONArray.fromObject(persons);
		System.out.println("----集合转换json----"+jsonArray.toString());
		
		//4.数组转换json
		// 同样用JSONObject 来放数组
		String arr[] = new String[]{"12","34","56"} ;
		JSONObject jsonObjectArr = new JSONObject();
		jsonObjectArr.put("name", arr);
		System.out.println("----数组转换json对象----"+jsonObjectArr.toString());
		
		// 5.map 转换json	
		// 可以用JSONObject直接来转换
		Map<String, Person> map = new HashMap<String, Person>();
		map.put("12", person);
		map.put("23", person2);
		JSONObject jsonmap = JSONObject.fromObject(map);
		System.out.println("----map转换json对象----"+jsonmap.toString());
		// 试试list 是否可以直接转换	
		// 'object' is an array. Use JSONArray instead  
		// 报错不可使用
//		JSONObject jsonlist = JSONObject.fromObject(persons);
//		System.out.println("----map转换json对象----"+jsonlist.toString());

		// 6.对象中有其他对象的json转换
		Student student = new Student();
		student.setAge(21);
		student.setName("liyong");
		person.setStudent(student);
		JSONObject jsonPerStu = JSONObject.fromObject(person);
		System.out.println("----对象包含对象----"+jsonPerStu.toString());
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值