Java 如何解析key為動態(tài)的json操作
'panel': { '8': { '112': 1 }, '11': { '147': 2 } }遍歷獲取Key和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());}
補充:Java利用反射動態(tài)獲取參數(shù)并進行操作實例,實現(xiàn)動態(tài)獲取實體類解析JSON
今天看到程序里面有大量數(shù)據(jù)都是使用的JSON傳輸,解析重復代碼太多了,然后重構(gòu)了解析JSON的方式,利用反射機制把解析的方式封裝了一下,我這是使用的FastJson,使用其他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; /** * 字符串工具類 * * @author wangchl */public class JsonUtils { /** * 獲取參數(shù)不為空值 * * @param method實體類 text:JSON字符串 * @return obj 返回值 */public static <T> Object Analysis(String method, String text) throwsClassNotFoundException {Class<?> p = Class.forName(method);JSONObject jsonArray = JSONObject.parseObject(text); try {Constructor con = p.getConstructor();Object obj = con.newInstance();// 獲取私有成員變量,并對它進行賦值for (Entry<String, Object> entry : jsonArray.entrySet()) { try { //設置KeyField newname = p.getDeclaredField(entry.getKey());// 取消私有成員變量語言訪問檢查public void setAccessible(boolean flag)newname.setAccessible(true); //value值為空不做任何操作if (!entry.getValue().equals('')) {newname.set(obj, entry.getValue());}} catch (NoSuchFieldException e) {// 解析JSON時實體類中沒有Key中的字段時會出現(xiàn)異常,忽略,不做任何處理}}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;}/** * *使用方式 * */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();}}///}
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。如有錯誤或未考慮完全的地方,望不吝賜教。
相關文章:
1. js select支持手動輸入功能實現(xiàn)代碼2. Android studio 解決logcat無過濾工具欄的操作3. 如何在PHP中讀寫文件4. Android 實現(xiàn)徹底退出自己APP 并殺掉所有相關的進程5. PHP正則表達式函數(shù)preg_replace用法實例分析6. php redis setnx分布式鎖簡單原理解析7. 什么是Python變量作用域8. Android Studio3.6.+ 插件搜索不到終極解決方案(圖文詳解)9. bootstrap select2 動態(tài)從后臺Ajax動態(tài)獲取數(shù)據(jù)的代碼10. vue使用moment如何將時間戳轉(zhuǎn)為標準日期時間格式
