JavaBean2Json.java 6.91 KB
package com.viontech.util;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.PropertyFilter;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.*;

@SuppressWarnings({"unchecked","deprecation"})
public class JavaBean2Json {

	public static String javaBean2Json(Object obj) {
		return JSONObject.fromObject(obj,getJsonConfig()).toString();
	}
	
	public static <T> T Json2JavaBean(String json,Class<T> clas) {
		try {
	        ObjectMapper om = new ObjectMapper();
	        om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
	        return om.readValue(json, clas);
        } catch (Exception e) {
        	JSONObject jsb = new JSONObject();
        	return (T) jsb.toBean(JSONObject.fromObject(json), clas, getJsonConfig());
        }
	}

	/**
	 * json转List
	 * @param json
	 * @param clazz
	 * @param <T>
	 * @return
	 */
	public static <T> List<T> json2List(String json,Class<T> clazz) {
		if(json.startsWith("[")){//json.indexOf("[")==0
			JSONArray array = JSONArray.fromObject(json);
			List<T> list = JSONArray.toList(array, clazz);
			return  list;
		}
       return null;
	}

	/**
	 * json转Array
	 * @param json
	 * @param clazz
	 * @param <T>
	 * @return
	 */
	public static <T> T[] json2Array(String json,Class<T> clazz) {
		if(json.indexOf("[")==0){
			JSONArray array = JSONArray.fromObject(json);
			 T[] ray = (T[]) JSONArray.toArray(array, clazz);
			return  ray;
		}
		return null;
	}
	private static JsonConfig getJsonConfig(){
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.setJsonPropertyFilter(new PropertyFilter() {
			public boolean apply(Object source/* 属性的拥有者 */, String name /* 属性名字 */,Object value/* 属性值 */) {
				if(value instanceof List){
                    List<Object> list = (List<Object>) value;
                    if (list == null || list.size()==0) {
                        return true;
                    }
                }else if(value instanceof Map){
                	Map map = (Map) value;
                    if (map == null || map.size() == 0) {
                        return true;
                    }
                }
				return null == value || "".equals(value);
			}
		});
		return jsonConfig;
	}
	public static void jsonToMap(String json, Map map) {
		JSONObject jsonObject = JSONObject.fromObject(json);
		populate(jsonObject, map);
	}

	private static void populate(JSONObject jsonObject, Map map) {
		for (Iterator iterator = jsonObject.entrySet().iterator(); iterator
				.hasNext();) {
			String entryStr = String.valueOf(iterator.next());
			String key = entryStr.substring(0, entryStr.indexOf("="));
			String value = entryStr.substring(entryStr.indexOf("=") + 1,entryStr.length());
			if (jsonObject.get(key).getClass().equals(JSONObject.class)) {
				HashMap _map = new HashMap();
				map.put(key, _map);
				populate(jsonObject.getJSONObject(key), ((Map) (_map)));
			} else if (jsonObject.get(key).getClass().equals(JSONArray.class)) {
				ArrayList list = new ArrayList();
				map.put(key, list);
				populateArray(jsonObject.getJSONArray(key), list);
			} else {
				map.put(key, jsonObject.get(key));
			}
		}
	}

	private static void populateArray(JSONArray jsonArray, List list) {
		for (int i = 0; i < jsonArray.size(); i++)
			if (jsonArray.get(i).getClass().equals(JSONArray.class)) {
				ArrayList _list = new ArrayList();
				list.add(_list);
				populateArray(jsonArray.getJSONArray(i), _list);
			} else if (jsonArray.get(i).getClass().equals(JSONObject.class)) {
				HashMap _map = new HashMap();
				list.add(_map);
				populate(jsonArray.getJSONObject(i), _map);
			} else {
				list.add(jsonArray.get(i));
			}
	}
	/***
	 * 判断发过来的信息是否是json格式
	 *
	 * @param json
	 * @return
	 */
	public static boolean isJson(String json) {
		try {
			JSONObject.fromObject(json);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	public static Object mulMapVal(Object object,String keys) {
		if (object != null) {
			String[] key = keys.split(",");
			for (int i=0;i<key.length;i++) {
				if (object instanceof Map) {
					Map dbobj = (Map) object;
					object = dbobj.get(key[i]);
				}
			}
			return object;
		}
		return null;
	}


	public static Map<String, Object> transBean2Map(Object obj) {
		if(obj == null){
			return null;
		}
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
			PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
			for (PropertyDescriptor property : propertyDescriptors) {
				String key = property.getName();
				// 过滤class属性
				if (!key.equals("class")) {
					// 得到property对应的getter方法
					Method getter = property.getReadMethod();
					Object value = getter.invoke(obj);
					map.put(key, value);
				}
			}
		} catch (Exception e) {
			System.out.println("transBean2Map Error " + e);
		}
		return map;
	}

	public static void main(String[] args) {
		Map<String, Object> map = new HashMap<>();
		String json="{\"id\":\"32\", \"vehicle\" : {\n" +
				"            \"global_feature\" : {\n" +
				"                \"AlignParameters\" : null, \n" +
				"                \"FeatureVector\" : null\n" +
				"            }, \n" +
				"            \"image\" : \"全景1\", \n" +
				"            \"local_feature\" : {\n" +
				"                \"FeatureVector\" : null, \n" +
				"                \"nFeatureCount\" : 1097913940\n" +
				"            }, \n" +
				"            \"plate\" : {\n" +
				"                \"char_count\" : 7, \n" +
				"                \"color_code\" : \"2\", \n" +
				"                \"color_name\" : \"蓝色\", \n" +
				"                \"head_text\" : \"京\", \n" +
				"                \"image\" : \"全景1\", \n" +
				"                \"other_text\" : \"RS5T48\", \n" +
				"                \"rect\" : {\n" +
				"                    \"bottom\" : 0.8336397, \n" +
				"                    \"left\" : 0.7838542, \n" +
				"                    \"right\" : 0.83177084, \n" +
				"                    \"top\" : 0.8134191\n" +
				"                }, \n" +
				"                \"score\" : 0, \n" +
				"                \"text\" : \"京RS5T48\", \n" +
				"                \"type_code\" : \"02\"\n" +
				"            }, \n" +
				"            \"rect\" : {\n" +
				"                \"bottom\" : 0.89966905, \n" +
				"                \"left\" : 0.66406256, \n" +
				"                \"right\" : 0.95156246, \n" +
				"                \"top\" : 0.61216915\n" +
				"            }\n" +
				"        }\n" +
				"\t\t}\n";
		JavaBean2Json.jsonToMap(json,map);
		System.out.println("map = " + map);
		String plate_text =(String) JavaBean2Json.mulMapVal(map, "vehicle,plate,text");
		System.out.println("plate_text = " + plate_text);
	}
}