日期:2014-05-16 浏览次数:20477 次
//1.对象 package com.hx.test; import com.hx.entity.Person; import net.sf.json.JSONObject; public class JsonTest { public static void main(String[] args) { Person person = new Person(); person.setName("tom"); person.setAddress("UK"); person.setAge(14); JSONObject json = JSONObject.fromObject(person); System.out.println(json.toString()); } } //输出结果为: //{"address":"UK","age":14,"name":"tom"} //2.数组和集合 package com.hx.test; import java.util.ArrayList; import java.util.List; import net.sf.json.JSONArray; public class JsonTest { public static void main(String[] args) { List<String> fruit = new ArrayList<String>(); fruit.add("apple"); fruit.add("pear"); fruit.add("orange"); fruit.add("banana"); JSONArray fruits = JSONArray.fromObject(fruit); System.out.println(fruits.toString()); } } //输出结果: //["apple","pear","orange","banana"] //2)Map集合 //Map集合比较特殊,因为 key-value键值对的对应方式,所以咱们应当用JSONObject来生成json。 package com.hx.test; import java.util.HashMap; import java.util.Map; import net.sf.json.JSONObject; public class JsonTest { public static void main(String[] args) { Map<String, String> map = new HashMap<String, String>(); map.put("001", "apple"); map.put("002", "pear"); map.put("003", "orange"); map.put("004", "banana"); JSONObject json = JSONObject.fromObject(map); System.out.println(json.toString()); } } //输出结果: //{"004":"banana","001":"apple","002":"pear","003":"orange"} //3) Map集合扩展 package com.hx.test; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import net.sf.json.JSONObject; public class JsonTest { public static void main(String[] args) { Map<String, List<String>> map = new HashMap<String, List<String>>(); List<String> strList1 = new ArrayList<String>(); strList1.add("aa"); strList1.add("bb"); strList1.add("cc"); List<String> strList2 = new ArrayList<String>(); strList2.add("dd"); strList2.add("ee"); strList2.add("ff"); List<String> strList3 = new ArrayList<String>(); strList3.add("gg"); strList3.add("hh"); strList3.add("ii"); map.put("001", strList1); map.put("002", strList2); map.put("003", strList3); JSONObject json = JSONObject.fromObject(map); System.out.println(json.toString()); } } //输出结果: //{"001":["aa","bb","cc"],"002":["dd","ee","ff"],"003":["gg","hh","ii"]} /* 和json-lib相比,Gson操作就相当的更简单了 不管是对象还是数组,还是上面较复杂的map集合, 操作都是一样的,Gson是出自google,应为比较小巧,所以其自己系统android上面用的也 是这个。 */ //因为操作都一样,所以在这里只给大家演示一种情况。 //别忘了导jar包:[i]gson-2.1.jar[/i] package com.hx.test; import com.google.gson.Gson; import com.hx.entity.Person; public class GsonTest { public static void main(String[] args) { Person person = new Person(); person.setAddress("UK"); person.setAge(14); person.setName("tom"); Gson gson = new Gson(); System.out.println(gson.toJson(person)); } } //输出结果: //{"name":"tom","age":14,"address":"UK"}