Json字串轉Json物件及Java物件
阿新 • • 發佈:2020-10-29
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 陣列 字串 轉JSONArrayString 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,遍歷即可。