//json entity transfer, list json transfer, List<Entity> to List<Object>, List<Objcet> to List<Map>

package mission;

//json entity interconversion, list json interconversion, List<entity> to List<Object>, List<Objcet> to List<Map> using alibaba's json toolkit

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by chengda on 2017/2/23.
 */
public class JsonTest {

	public static void main(String[] args) {
		List<Brand> brandList = new ArrayList<Brand>();
		Brand b = new Brand();
		b.setId(1);
		b.setName("Test");
		b.setStatus(false);
		Brand b1 = new Brand();
		b1.setId(2);
		b1.setName("Test 2");
		b1.setStatus(false);
		Brand b2 = new Brand();
		b2.setId(3);
		b2.setName("Test 3");
		b2.setStatus(false);

		brandList.add(b1);
		brandList.add(b2);
		brandList.add(b);

		/**
		 * Entity is converted to json String string
		 */
		String s = JSONObject.toJSONString(b);
		System.out.println(s);

		/**
		 * json String string to JSONObject
		 */
		JSONObject ss = JSONObject.parseObject(s);
		System.out.println(ss.getBooleanValue("status"));

		/**
		 * Convert JSONObject to String
		 * String to Map
		 */
		String sss = JSON.toJSONString(ss);
		Map maps = JSONObject.parseObject(sss, Map.class);
		for(Object object : maps.keySet()) {
			System.out.println("key=" + object + " value=" + maps.get(object));  
		}
		
		
		/**
		 *
		 * json to entity
		 */
		Brand brand = JSONObject.parseObject(s, Brand.class);
		System.out.println(brand + "==============");

		/**
		 *
		 * list collection to json
		 */
		String s1 = JSON.toJSONString(brandList);
		System.out.println(s1 + "999999");
		// json to list
		List<Brand> brands = JSONObject.parseArray(s1, Brand.class);
		System.out.println(brands);

	}

	/**
	 * List<Entity> to list<Object>
	 *
	 * @param t
	 * @return
	 */
	public List<Object> beanToObject(List<?> t) {
		List<Object> o = new ArrayList<Object>();
		Iterator<?> it = t.iterator();
		while (it.hasNext()) {
			o.add(it.next());
		}

		return o;
	}

	/**
	 * List<objcet> to List<Map>
	 *
	 * @param object
	 * @return
	 * @throws Exception
	 */
	public List<Map> beanToMap(List<Object> object) throws Exception {
		List<Map> maps = new ArrayList<Map>();
		for (Object o : object) {
			String s = JSON.toJSONString(o);
			Map map = JSONObject.parseObject(s, Map.class);

			maps.add(map);
		}
		return maps;
	}


	/**
	 * map to entity
	 */
	public static <T> T toBean(Class<T> clazz, Map map) {
		T obj = null;
		try {
			BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
			obj = clazz.newInstance(); // create a JavaBean object

			// Assign values ​​to properties of the JavaBean object
			PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
			for (int i = 0; i < propertyDescriptors.length; i++) {
				PropertyDescriptor descriptor = propertyDescriptors[i];
				String propertyName = descriptor.getName();
				if (map.containsKey(propertyName)) {
					// The following sentence can be tried, so that when a property assignment fails, it will not affect other property assignments.
					Object value = map.get(propertyName);
					if ("".equals(value)) {
						value = null;
					}
					Object[] args = new Object[1];
					args[0] = value;
					try {
						descriptor.getWriteMethod().invoke(obj, args);
					} catch (InvocationTargetException e) {
						System.out.println("Field mapping failed");
					}
				}
			}
		} catch (IllegalAccessException e) {
			System.out.println("Failed to instantiate JavaBean");
		} catch (IntrospectionException e) {
			System.out.println("Failed to analyze class properties");
		} catch (IllegalArgumentException e) {
			System.out.println("Mapping error");
		} catch (InstantiationException e) {
			System.out.println("Failed to instantiate JavaBean");
		}
		return (T) obj;
	}
}

    

public static final Object parse(String text); // Parse JSON text into JSONObject or JSONArray
public static final JSONObject parseObject(String text); // Parse JSON text into JSONObject    
public static final <T> T parseObject(String text, Class<T> clazz); // parse JSON text into JavaBean
public static final JSONArray parseArray(String text); // Parse JSON text into JSONArray
public static final <T> List<T> parseArray(String text, Class<T> clazz); //parse JSON text into JavaBean collection
public static final String toJSONString(Object object); // Serialize JavaBean to JSON text
public static final String toJSONString(Object object, boolean prettyFormat); // Serialize JavaBean to formatted JSON text
public static final Object toJSON(Object javaObject); Convert JavaBean to JSONObject or JSONArray.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326259685&siteId=291194637