Java 如何解析key為動(dòng)態(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());}
補(bǔ)充:Java利用反射動(dòng)態(tài)獲取參數(shù)并進(jìn)行操作實(shí)例,實(shí)現(xiàn)動(dòng)態(tài)獲取實(shí)體類解析JSON
今天看到程序里面有大量數(shù)據(jù)都是使用的JSON傳輸,解析重復(fù)代碼太多了,然后重構(gòu)了解析JSON的方式,利用反射機(jī)制把解析的方式封裝了一下,我這是使用的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實(shí)體類 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();// 獲取私有成員變量,并對(duì)它進(jìn)行賦值for (Entry<String, Object> entry : jsonArray.entrySet()) { try { //設(shè)置KeyField newname = p.getDeclaredField(entry.getKey());// 取消私有成員變量語(yǔ)言訪問(wèn)檢查public void setAccessible(boolean flag)newname.setAccessible(true); //value值為空不做任何操作if (!entry.getValue().equals('')) {newname.set(obj, entry.getValue());}} catch (NoSuchFieldException e) {// 解析JSON時(shí)實(shí)體類中沒(méi)有Key中的字段時(shí)會(huì)出現(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();}}///}
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章:
1. CSS3實(shí)例分享之多重背景的實(shí)現(xiàn)(Multiple backgrounds)2. HTML DOM setInterval和clearInterval方法案例詳解3. 告別AJAX實(shí)現(xiàn)無(wú)刷新提交表單4. 使用css實(shí)現(xiàn)全兼容tooltip提示框5. CSS hack用法案例詳解6. 低版本IE正常運(yùn)行HTML5+CSS3網(wǎng)站的3種解決方案7. css進(jìn)階學(xué)習(xí) 選擇符8. 使用純HTML的通用數(shù)據(jù)管理和服務(wù)9. css代碼優(yōu)化的12個(gè)技巧10. Vue+elementUI下拉框自定義顏色選擇器方式
