Java development data type conversion

Convert Java entity classes to Map

Note: This small tool class can map the direct value properties of the Java object to map, but it fails to map all the properties of the child object structure (which is what I need), and it fails to map the properties of obj inherited from the parent class. The inherited attributes need to be mapped to the map and need to be added manually.

public class MapUtils
{
   public static Map<String,Object> ConvertObjToMap(Object obj){
		  Map<String,Object> reMap = new HashMap<String,Object>();
		  if (obj == null) 
		   return null;
		  Field[] fields = obj.getClass().getDeclaredFields();
		  try {
		   for(int i=0;i<fields.length;i++){
		    try {
		     Field f = obj.getClass().getDeclaredField(fields[i].getName());
		     f.setAccessible(true);
		           Object o = f.get(obj);
		           reMap.put(fields[i].getName(), o);
		    } catch (NoSuchFieldException e) {
		     // TODO Auto-generated catch block
		     e.printStackTrace();
		    } catch (IllegalArgumentException e) {
		     // TODO Auto-generated catch block
		     e.printStackTrace();
		    } catch (IllegalAccessException e) {
		     // TODO Auto-generated catch block
		     e.printStackTrace();
		    }
		   }
		  } catch (SecurityException e) {
		   // TODO Auto-generated catch block
		   e.printStackTrace();
		  } 
		  return reMap;
		 }
}

Test call: where objTemp is a Java class:

//调用实例:
Map<String, Object> mapTemp = MapUtils.object2Map(objTemp);

Convert Java Map to JsonObject

I use fastjson, but because fastjson directly calls JSONObject.parseObject(javaObject) to convert Java objects to json, if javaObject nests child objects, the conversion result is not friendly at this time, so I will transfer the object to Map first. To json (a bit verbose.)

JSONObject jsonObject = new JSONObject(mapTemp);

Json into Java entity object

public class MyJavaClass
{
    //TODO 
}

//调用实例:
String jsonStr = "{}";
MyJavaClass myjavaClass = JSON.parseObject(jsonStr, MyJavaClass.class);

Convert JSONObject to entity class

As follows, I use fastjson to convert JSONObject to the writing format of the Java class MyJavaClass:

public class MyJavaClass
{
    //TODO
}

void test()
{
   JSONObject jsonObj;
   MyJavaClass info = JSONObject.toJavaObject(jsonObj,MyJavaClass.class);
}

Convert JSONObject to Map:

The following is to convert myJsonObj's JSONObject to Map<String,Object>

JSONObject myJsonObj = null;//TODO 
Map<String, Object> itemMap = JSONObject.toJavaObject(myJsonObj, Map.class);

Guess you like

Origin blog.csdn.net/Stephanie_1/article/details/108711584