Json字符串轉Java對象
//json 字符串 轉Java對象 String confStr = "{\"key\":\"nihk\",\"secret\":\"qq123456\"}"; JSONObject jsonObject = JSONObject.parseObject(confStr); AuthConf conf = JSONObject.toJavaObject(jsonObject, AuthConf.class); System.out.println("conf=" + conf); // json 數組 字符串 轉JSONArray String confStr = "[{\"key\":\"nihk\"},{\"key\":\"nihk2\"}]"; JSONArray jarr = JSONArray.parseArray(confStr);
// 以下方法得到的是JSONArray List<AuthConf> conf2 = JSONObject.toJavaObject(jarr, List.class); System.out.println("conf2=" + conf2); List<AuthConf> conf22 = JSONArray.toJavaObject(jarr, List.class); System.out.println("conf22=" + conf22); List<AuthConf> conf222 = JSON.toJavaObject(jarr, List.class); System.out.println("conf222=" + conf222); //輸出 conf=AuthConf(key=nihk, secret=qq123456) conf2=[{"key":"nihk"},{"key":"nihk2"}] conf22=[{"key":"nihk"},{"key":"nihk2"}] conf222=[{"key":"nihk"},{"key":"nihk2"}]
說明:
如果是json 字符串,則采用JSONObject.parseObject(confStr)轉換成對象;
如果是json數組字符串采用JSONArray jarr = JSONArray.parseArray(confStr);
轉換成對象AuthConf conf = JSONObject.toJavaObject(jsonObject, AuthConf.class)
如果是JSONArray,遍歷即可。