Intertransform method based on JSON and java objects

  • 2020-10-23 20:59:01
  • OfStack

In general, to convert JSON string into java object, you need to write an entity class bean which is similar to JSON1, and then pass it to the corresponding method with bean.class as a parameter to achieve successful conversion.

This method is too cumbersome. In fact, there is one thing called jsonObject, which can be converted directly without creating a new entity class bean. First say org.json.JSONObject, and paste the code:


import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.json.JSONObject;

/**
* Json The utility class implements the entity class and Json Interoperability between data formats   Examples of use: <br>
*/
public class JsonUtils {
 /**
  *  will 1 An entity class object is converted to Json The data format 
  * 
  * @param bean
  *    The entity class object that needs to be transformed 
  * @return  The transformed Json Format string 
  */
 private static String beanToJson(Object bean) {
  StringBuilder json = new StringBuilder();
  json.append("{");
  PropertyDescriptor[] props = null;
  try {
   props = Introspector.getBeanInfo(bean.getClass(), Object.class)
     .getPropertyDescriptors();
  } catch (IntrospectionException e) {
  }
  if (props != null) {
   for (int i = 0; i < props.length; i++) {
    try {
     String name = objToJson(props[i].getName());
     String value = objToJson(props[i].getReadMethod()
       .invoke(bean));
     json.append(name);
     json.append(":");
     json.append(value);
     json.append(",");
    } catch (Exception e) {
    }
   }
   json.setCharAt(json.length() - 1, '}');
  } else {
   json.append("}");
  }
  return json.toString();
 }


 /**
  *  will 1 a List Object conversion to Json Data format return 
  * 
  * @param list
  *    It needs to be converted List object 
  * @return  The transformed Json Data format string 
  */
 private static String listToJson(List<?> list) {
  StringBuilder json = new StringBuilder();
  json.append("[");
  if (list != null && list.size() > 0) {
   for (Object obj : list) {
    json.append(objToJson(obj));
    json.append(",");
   }
   json.setCharAt(json.length() - 1, ']');
  } else {
   json.append("]");
  }
  return json.toString();
 }

 /**
  *  will 1 An array of objects Json Data format return 
  * 
  * @param array
  *    The array object that needs to be transformed 
  * @return  The transformed Json Data format string 
  */
 private static String arrayToJson(Object[] array) {
  StringBuilder json = new StringBuilder();
  json.append("[");
  if (array != null && array.length > 0) {
   for (Object obj : array) {
    json.append(objToJson(obj));
    json.append(",");
   }
   json.setCharAt(json.length() - 1, ']');
  } else {
   json.append("]");
  }
  return json.toString();
 }

 /**
  *  will 1 a Map Object conversion to Json Data format return 
  * 
  * @param map
  *    It needs to be converted Map object 
  * @return  The transformed Json Data format string 
  */
 private static String mapToJson(Map<?, ?> map) {
  StringBuilder json = new StringBuilder();
  json.append("{");
  if (map != null && map.size() > 0) {
   for (Object key : map.keySet()) {
    json.append(objToJson(key));
    json.append(":");
    json.append(objToJson(map.get(key)));
    json.append(",");
   }
   json.setCharAt(json.length() - 1, '}');
  } else {
   json.append("}");
  }
  return json.toString();
 }

 /**
  *  will 1 a Set Object conversion to Json Data format return 
  * 
  * @param set
  *    It needs to be converted Set object 
  * @return  The transformed Json Data format string 
  */
 private static String setToJson(Set<?> set) {
  StringBuilder json = new StringBuilder();
  json.append("[");
  if (set != null && set.size() > 0) {
   for (Object obj : set) {
    json.append(objToJson(obj));
    json.append(",");
   }
   json.setCharAt(json.length() - 1, ']');
  } else {
   json.append("]");
  }
  return json.toString();
 }

 private static String stringToJson(String s) {
  if (s == null) {
   return "";
  }
  StringBuilder sb = new StringBuilder();
  for (int i = 0; i < s.length(); i++) {
   char ch = s.charAt(i);
   switch (ch) {
   case '"':
    sb.append("\\\"");
    break;
   case '\\':
    sb.append("\\\\");
    break;
   case '\b':
    sb.append("\\b");
    break;
   case '\f':
    sb.append("\\f");
    break;
   case '\n':
    sb.append("\\n");
    break;
   case '\r':
    sb.append("\\r");
    break;
   case '\t':
    sb.append("\\t");
    break;
   case '/':
    sb.append("\\/");
    break;
   default:
    if (ch >= '\u0000' && ch <= '\u001F') {
     String ss = Integer.toHexString(ch);
     sb.append("\\u");
     for (int k = 0; k < 4 - ss.length(); k++) {
      sb.append('0');
     }
     sb.append(ss.toUpperCase());
    } else {
     sb.append(ch);
    }
   }
  }
  return sb.toString();
 }

 public static String objToJson(Object obj) {
  StringBuilder json = new StringBuilder();
  if (obj == null) {
   json.append("\"\"");
  } else if (obj instanceof Number) {
   Number num = (Number)obj;
   json.append(num.toString());
  } else if (obj instanceof Boolean) {
   Boolean bl = (Boolean)obj;
   json.append(bl.toString());
  } else if (obj instanceof String) {
   json.append("\"").append(stringToJson(obj.toString())).append("\"");
  } else if (obj instanceof Object[]) {
   json.append(arrayToJson((Object[]) obj));
  } else if (obj instanceof List) {
   json.append(listToJson((List) obj));
  } else if (obj instanceof Map) {
   json.append(mapToJson((Map) obj));
  } else if (obj instanceof Set) {
   json.append(setToJson((Set) obj));
  } else {
   json.append(beanToJson(obj));
  }
  return json.toString();
 }
 
 /**
  * @Title: json2Map
  * @Creater: chencc <br>
  * @Date: 2011-3-28 <br>
  * @Description: TODO conversion json2map
  * @param @param jsonString
  * @param @return
  * @return Map<String,Object>
  * @throws
  */
 @SuppressWarnings("unchecked")
 public static Map<String, Object> json2Map(String jsonString) {
  
  Map<String, Object> map = new HashMap<String, Object>();
  try {
   if(null != jsonString && !"".equals(jsonString)){
    JSONObject jsonObject = new JSONObject(jsonString);
   
    Iterator keyIter = jsonObject.keys();
    String key = "";
    Object value = null;
   
    while (keyIter.hasNext()) {
     key = (String) keyIter.next();
     value = jsonObject.get(key);
     map.put(key, value);
    }
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
  return map;
 }
 
 // The test method 
 public static void main(String[] args) {
  Map<String,Object> params = new HashMap<String,Object>();
  params.put("callId123", Integer.valueOf(1000));
  Map retMap = new HashMap();
  retMap.put("params", params);
  retMap.put("result", true);
  List ls = new ArrayList();
  ls.add(new HashMap());
  ls.add("hello world!!");
  ls.add(new String[4]);
  retMap.put("list", ls);
  
  String[] strArray = new String[10];
  strArray[1]="first";
  strArray[2]="2";
  strArray[3]="3";
  System.out.println("Boolean:"+JsonUtils.objToJson(true));
  System.out.println("Number:"+JsonUtils.objToJson(23.3));
  System.out.println("String:"+JsonUtils.objToJson("sdhfsjdgksdlkjfk\"sd,!#%$^&*#(*@&*%&*$fsdfsdfsdf"));
  System.out.println("Map :"+JsonUtils.objToJson(retMap));
  System.out.println("List:"+JsonUtils.objToJson(ls));
  System.out.println("Array:"+JsonUtils.objToJson(strArray));
  
  String json = JsonUtils.objToJson(retMap);
  Map r = JsonUtils.json2Map(json);
  System.out.println(r.get("callId123"));
  
  
 }
}

Chat again net. sf. json. JSONObject this JSONObject, code is as follows


import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.CycleDetectionStrategy;
import net.sf.json.util.PropertyFilter;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonUtil {
 
 
 private static ObjectMapper objectMapper = null;
 /**
  * JSON Initialize the 
  */
 static {
  objectMapper = new ObjectMapper(); 
  // Set to China Shanghai time zone  
  objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+8")); 
  // Null values are not serialized  
  objectMapper.setSerializationInclusion(Include.NON_NULL); 
  // When deserializing, there is no compatibility processing for the property  
  objectMapper.getDeserializationConfig().withoutFeatures(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); 
  // When serialized, the date series 1 format  
  objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); 

  objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); 
  
 } 
 
 
 /**
  *  Convert the object to Json string 
  *
  * @param obj
  * @return
  */
 public static String convertObjectToJson(Object obj) {
  if (obj == null) {
//    throw new IllegalArgumentException(" The object parameter cannot be null. ");
   return null;
  }
  try {
   return objectMapper.writeValueAsString(obj);

  } catch (IOException e) {
   e.printStackTrace();
  }
  return null;

 }
 /**
  *  the json String conversion to Object object 
  * @param jsonString
  * @return T
  */
 public static <T> T parseJsonToObject(String jsonString, Class<T> valueType) {
  
  if(jsonString == null || "".equals((jsonString))){
   return null;
  }
  try {
   return objectMapper.readValue(jsonString, valueType);
  } catch (Exception e) {
   e.printStackTrace();
  }
  return null;
 }
 /**
  *  the json String conversion to List object 
  * @param jsonString
  * @return List<T>
  */
 @SuppressWarnings("unchecked")
 public static <T> List<T> parseJsonToList(String jsonString,Class<T> valueType) {
  
  if(jsonString == null || "".equals((jsonString))){
   return null;
  }
  
  List<T> result = new ArrayList<T>();
  try {
   List<LinkedHashMap<Object, Object>> list = objectMapper.readValue(jsonString, List.class);
   
   for (LinkedHashMap<Object, Object> map : list) {
    
    String jsonStr = convertObjectToJson(map);
    
    T t = parseJsonToObject(jsonStr, valueType);
    
    result.add(t);
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
  return result;
 }
 /**
  * JSON Handle objects containing nested relationships to avoid exceptions: net.sf.json.JSONException: There is a cycle in the hierarchy The method of 
  *  Note: In the resulting string, the property causing the nested loop is set to null
  *
  * @param obj
  * @return
  */
 public static JSONObject getJsonObject(Object obj) {

  JsonConfig jsonConfig = new JsonConfig();
  jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
  jsonConfig.setJsonPropertyFilter(new PropertyFilter() {
   
   @Override
   public boolean apply(Object source, String name, Object value) {
    if(value==null){
     return true;
    }
    return false;
   }
  });
  return JSONObject.fromObject(obj, jsonConfig);
 }
 /**
  * JSON Handle objects containing nested relationships to avoid exceptions: net.sf.json.JSONException: There is a cycle in the hierarchy The method of 

  *  Note: In the resulting string, the property causing the nested loop is set to null
  *
  * @param obj
  * @return
  */
 public static JSONArray getJsonArray(Object obj) {

  JsonConfig jsonConfig = new JsonConfig();
  jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);

  return JSONArray.fromObject(obj, jsonConfig);
 }
 /**
  *  parsing JSON The string into a 1 a MAP
  *
  * @param jsonStr json A string in a format such as:  {dictTable:"BM_XB",groupValue:" Grouping values "}
  * @return
  */
 public static Map<String, Object> parseJsonStr(String jsonStr) {

  Map<String, Object> result = new HashMap<String, Object>();

  JSONObject jsonObj = JsonUtil.getJsonObject(jsonStr);

  for (Object key : jsonObj.keySet()) {
   result.put((String) key, jsonObj.get(key));
  }
  return result;
 }

}

Summary: net sf. json. JSONObject this belongs to the series of json - lib the veteran, super more rely on the package, commons lang, logging, beanutils, collections component has.

org.json, on the other hand, relies on a relatively small number of packages, with little testing for speed and performance.


Related articles: