1.JSON介绍
JSON比XML简单,主要体现在传输相同信息的情况下,文件的大小不同。
JSON只用于传输信息,XML还可以用于配置文件的使用。
JSON中的符号主要有: " , [ {:
2.JSON中的数组和对象
2.1数组(JSONArray)
数组用一对[],表示存放的是一般的数组数据。
如:["11","22","33"],表示这是一个JSONArray数组,里面有3个数据:”11“,”22“,”33“。当然可以是复杂的数据,就是所谓的嵌套定义吧。
2.对象(JSONObject)
对象用一对{},来表示其中JSON通用的”键-值“对。
如:{"sex1":"female","name0":"zhangsan"},表示的是一个JSON对象,里面有两组数据(键值对),sex1=female,name0=zhangsan。当然这里键对应的数据值,可以是复杂的JSON对象或者数组。
3.代码示例
- package com.somnus.json;
-
- import java.lang.reflect.Field;
- import java.util.ArrayList;
- import java.util.Date;
- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.List;
- import java.util.Map;
-
- import net.sf.json.JSONArray;
- import net.sf.json.JSONObject;
- import net.sf.json.JsonConfig;
- import net.sf.json.processors.JsDateJsonValueProcessor;
- import net.sf.json.util.CycleDetectionStrategy;
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- public class JsonUtil {
-
- private static JsonConfig configJson(String[] excludes) {
- JsonConfig jsonConfig = new JsonConfig();
- jsonConfig.setExcludes(excludes);
- jsonConfig.setIgnoreDefaultExcludes(false);
- jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
- jsonConfig.registerJsonValueProcessor(Date.class, new JsDateJsonValueProcessor());
- return jsonConfig;
- }
-
-
-
-
-
-
-
- public static String obj2JsonString(Object obj) {
- JSONObject json = JSONObject.fromObject(obj);
- return json.toString();
- }
-
-
-
-
-
-
-
-
-
-
- public static String obj2JsonString(Object obj, String[] include, boolean nory) {
- JSONObject json = null;
-
- if (nory){
- Field[] fields = obj.getClass().getDeclaredFields();
- String str = "";
- for (Field field : fields) {
- str += ("#" + field.getName());
- }
- fields = obj.getClass().getSuperclass().getDeclaredFields();
- for (Field field : fields) {
- str += ("#" + field.getName());
- }
- str += "#";
- for (String s : include) {
- str = str.replace("#" + s + "#", "#");
- }
- json = JSONObject.fromObject(obj, configJson(str.split(":")));
- }
-
- else {
- json = JSONObject.fromObject(obj, configJson(include));
- }
- return json.toString();
- }
-
-
-
-
-
-
-
- public static <E> String list2JsonString(List<E> list) {
- StringBuffer temp = new StringBuffer();
- temp.append("[");
- int size = list.size();
- for (int i = 0; i < size; i++) {
- temp.append(obj2JsonString(list.get(i)) + ((i < size - 1) ? "," : ""));
- }
- temp.append("]");
- return temp.toString();
- }
-
- public static <E> String list2JsonString_(List<E> list) {
- JSONArray jsonArray = JSONArray.fromObject(list);
- return jsonArray.toString();
- }
-
-
-
-
-
-
-
-
-
-
-
- public static <E> String list2JsonString(List<E> beans, String[] include, boolean nory) {
- StringBuffer rest = new StringBuffer();
- rest.append("[");
- int size = beans.size();
- for (int i = 0; i < size; i++) {
- rest.append(obj2JsonString(beans.get(i), include, nory) + ((i < size - 1) ? "," : ""));
- }
- rest.append("]");
- return rest.toString();
- }
-
-
-
-
-
-
-
-
- @SuppressWarnings("unchecked")
- public static <E, V> String map2JsonString(Map<E, V> map, String[] include, boolean nory) {
- String s_json = "{";
- for (Iterator<E> it = map.keySet().iterator(); it.hasNext();) {
- String key = (String) it.next();
- if (map.get(key) == null) {
- } else if (map.get(key) instanceof List) {
- s_json += ("\"" + key + "\":" + JsonUtil.list2JsonString((List<E>) map.get(key), include, nory));
- } else {
- JSONObject json = JSONObject.fromObject(map.get(key));
- s_json += ("\"" + key + "\":" + json.toString());
- }
- if (it.hasNext()) {
- s_json += ",";
- }
- }
- s_json += "}";
- return s_json;
- }
-
-
-
-
-
-
-
-
-
-
- @SuppressWarnings("unchecked")
- public static <T> T jsonString2Object(String jsonString, Class<T> clazz) {
- JSONObject jsonObject = JSONObject.fromObject(jsonString);
- T bean = (T) JSONObject.toBean(jsonObject, clazz);
- return bean;
- }
-
-
-
-
-
-
-
- @SuppressWarnings({ "unchecked" })
- public static<E, V> Map<E, V> jsonString2Map(String jsonString) {
- JSONObject jsonObject = JSONObject.fromObject(jsonString);
- Iterator<E> keyIter = jsonObject.keys();
- E key;
- V value;
- Map<E, V> valueMap = new HashMap<E, V>();
- while (keyIter.hasNext()) {
- key = (E)keyIter.next();
- value = (V)jsonObject.get(key);
- valueMap.put(key, value);
- }
- return valueMap;
- }
-
-
-
-
-
-
-
-
- @SuppressWarnings("unchecked")
- public static <T> List<T> json2ObjectList(String jsonString, Class<T> beanClass) {
- JSONArray jsonArray = JSONArray.fromObject(jsonString);
- JSONObject jsonObject;
- T bean;
- int size = jsonArray.size();
- List<T> list = new ArrayList<T>(size);
- for (int i = 0; i < size; i++) {
- jsonObject = jsonArray.getJSONObject(i);
- bean = (T) JSONObject.toBean(jsonObject, beanClass);
- list.add(bean);
- }
- return list;
- }
-
-
-
-
-
-
-
- public static Object[] jsonToObjectArray(String jsonString) {
- JSONArray jsonArray = JSONArray.fromObject(jsonString);
- return jsonArray.toArray();
- }
-
-
-
-
-
-
-
- public static String[] jsonToStringArray(String jsonString) {
- JSONArray jsonArray = JSONArray.fromObject(jsonString);
- String[] stringArray = new String[jsonArray.size()];
- int size = jsonArray.size();
- for (int i = 0; i < size; i++) {
- stringArray[i] = jsonArray.getString(i);
- }
- return stringArray;
- }
-
-
-
-
-
-
-
- public static Long[] jsonToLongArray(String jsonString) {
- JSONArray jsonArray = JSONArray.fromObject(jsonString);
- int size = jsonArray.size();
- Long[] longArray = new Long[size];
- for (int i = 0; i < size; i++) {
- longArray[i] = jsonArray.getLong(i);
- }
- return longArray;
- }
-
-
-
-
-
-
-
- public static Integer[] jsonToIntegerArray(String jsonString) {
- JSONArray jsonArray = JSONArray.fromObject(jsonString);
- int size = jsonArray.size();
- Integer[] integerArray = new Integer[size];
- for (int i = 0; i < size; i++) {
- integerArray[i] = jsonArray.getInt(i);
- }
- return integerArray;
- }
-
-
-
-
-
-
-
- public static Double[] jsonToDoubleArray(String jsonString) {
- JSONArray jsonArray = JSONArray.fromObject(jsonString);
- int size = jsonArray.size();
- Double[] doubleArray = new Double[size];
- for (int i = 0; i < size; i++) {
- doubleArray[i] = jsonArray.getDouble(i);
- }
- return doubleArray;
- }
-
- public static void main(String[] args) {
- User user = new User();
- user.setUsername("admin");
- user.setPassword("123");
- user.setAge(20);
- User user2 = new User();
- user2.setUsername("admin2");
- user2.setPassword("123456");
- user2.setAge(24);
- System.out.println("一:" + JsonUtil.obj2JsonString(user));
-
- Map<String, String> map11 = new HashMap<String, String>();
- map11.put("1", "a");
- map11.put("2", "b");
- System.out.println("二:" + JsonUtil.obj2JsonString(map11));
-
- System.out.println("****************************************************************");
- List<User> list = new ArrayList<User>();
- list.add(user);
- list.add(user2);
- System.out.println("三:" + JsonUtil.list2JsonString(list));
- System.out.println("四:" + JsonUtil.list2JsonString_(list));
-
- System.out.println("****************************************************************");
-
- System.out.println("五:" + JsonUtil.obj2JsonString(user, new String[] { "username" }, true));
-
- System.out.println("六:" + JsonUtil.obj2JsonString(user, new String[] { "username" }, false));
-
- System.out.println("七:" + JsonUtil.list2JsonString(list, new String[] { "username", "password" }, true));
-
- System.out.println("****************************************************************");
- Map<String, User> map1 = new HashMap<String, User>();
- map1.put("1", user);
- map1.put("2", user2);
- System.out.println("八:" + JsonUtil.map2JsonString(map1, new String[] { "username", "password" }, true));
-
- Map<String, List<User>> map2 = new HashMap<String, List<User>>();
- map2.put("1", list);
- System.out.println("九:" + JsonUtil.map2JsonString(map2, new String[] { "username", "password" }, true));
-
- }
-
- }
打印结果:
一:{"username":"admin","age":20,"password":"123"}
二:{"2":"b","1":"a"}
****************************************************************
三:[{"username":"admin","age":20,"password":"123"},{"username":"admin2","age":24,"password":"123456"}]
四:[
{"username":"admin","age":20,"password":"123"},
{"username":"admin2","age":24,"password":"123456"}
]
****************************************************************
五:{"username":"admin","age":20,"password":"123"}
六:{"age":20,"password":"123"}
七:[{"username":"admin","age":20,"password":"123"},{"username":"admin2","age":24,"password":"123456"}]
****************************************************************
八:{"2":{"username":"admin2","age":24,"password":"123456"},"1":{"username":"admin","age":20,"password":"123"}}
九:{"1":[{"username":"admin","age":20,"password":"123"},{"username":"admin2","age":24,"password":"123456"}]}
****************************************************************
十:[{"username":"admin","age":20,"password":"123"},{"username":"admin2","age":24,"password":"123456"}]
十一:{"2":{"username":"admin2","age":24,"password":"123456"},"1":{"username":"admin","age":20,"password":"123"}}
十二:{"1":[{"username":"admin","age":20,"password":"123"},{"username":"admin2","age":24,"password":"123456"}]}