How does Java resolve key as a dynamic json operation

  • 2021-08-21 20:40:39
  • OfStack

Encountered such an json string:


"panel": {
    "8": {
      "112": 1
    },
    "11": {
      "147": 2
    }
  }

Traversing for Key and Value


LinkedHashMap<String, String> jsonMap = JSON.parseObject(jsonStr, new TypeReference<LinkedHashMap<String, String>>(){});
for (Map.Entry<String, String> entry : jsonMap.entrySet()) {
  System.out.println(entry.getKey() + ":" + entry.getValue());
}

Supplement: Java uses reflection to dynamically obtain parameters and carry out operation examples to realize dynamic acquisition of entity class analysis JSON

Today, I see that there are a lot of data in the program that are transmitted by JSON, and there are too many repeated codes for analysis. Then I reconstruct the way of analyzing JSON, and use the reflection mechanism to encapsulate the way of analysis. I use FastJson, and I can change it by myself with other JSON


import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.Map.Entry; 
import com.alibaba.fastjson.JSONObject;
import com.zwsd.project.system.user.domain.User;
 
/**
 *  String tool class 
 * 
 * @author wangchl
 */
public class JsonUtils {
 
	/**
	 *  Get parameter is not null 
	 * 
	 * @param  method Entity class      text : JSON String  
	 * @return obj  Return value 
	 */
	public static <T> Object Analysis(String method, String text) throws      
  ClassNotFoundException {
		Class<?> p = Class.forName(method);
		JSONObject jsonArray = JSONObject.parseObject(text);
 
		try {
			Constructor con = p.getConstructor();
			Object obj = con.newInstance();
			//  Gets a private member variable and assigns a value to it 
			for (Entry<String, Object> entry : jsonArray.entrySet()) {
 
				try {
          // Settings Key
					Field newname = p.getDeclaredField(entry.getKey());
					//  Cancel the language access check of private member variables public void setAccessible(boolean flag)
					newname.setAccessible(true);
          //value Do nothing if the value is null 
					if (!entry.getValue().equals("")) {
						newname.set(obj, entry.getValue());
					}
				} catch (NoSuchFieldException e) {
					//  Analyse JSON Is not in the entity class Key Exception will occur when the field in, ignore, and do nothing 
				}
			}
			return obj;
			
		} catch (NoSuchMethodException e1) {
			e1.printStackTrace();
		} catch (SecurityException e1) {
			e1.printStackTrace();
		} catch (InstantiationException e1) {
			e1.printStackTrace();
		} catch (IllegalAccessException e1) {
			e1.printStackTrace();
		} catch (IllegalArgumentException e1) {
			e1.printStackTrace();
		} catch (InvocationTargetException e1) {
			e1.printStackTrace();
		}
		return null;
	}
	/**
	 * 
	 * Usage 
	 *
	 */
	public static void main(String[] args) {
		try {
			String text = " 
      {\"flag\":\"0\",\"token\":\"0b4b2ef3fed24c99b10c4fca65a09632\"}";
			User user= (User) JsonUtils.Analysis(User.class.getName(), text);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}///
}

Related articles: