| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- package cn.com.lzt.tools;
- import java.io.IOException;
- import java.util.List;
- import net.sf.json.JSONArray;
- import net.sf.json.JSONObject;
- import org.codehaus.jackson.map.ObjectMapper;
- import org.jeecgframework.web.system.pojo.base.TSUser;
- import org.json.JSONException;
- public class JsonTools {
- /**
- * 将json转化为实体POJO
- * @param jsonStr
- * @param obj
- * @return
- */
- public static<T> Object JSONToObj(String jsonStr,Class<T> obj) {
- T t = null;
- try {
- ObjectMapper objectMapper = new ObjectMapper();
- t = objectMapper.readValue(jsonStr,
- obj);
- } catch (Exception e) {
- e.printStackTrace();
- }
- return t;
- }
- /**
- * 将实体POJO转化为JSON
- * @param obj
- * @return
- * @throws JSONException
- * @throws IOException
- */
- // public static<T> JSONObject objectToJson(T obj) throws JSONException, IOException {
- // ObjectMapper mapper = new ObjectMapper();
- // // Convert object to JSON string
- // String jsonStr = "";
- // try {
- // jsonStr = mapper.writeValueAsString(obj);
- // } catch (IOException e) {
- // throw e;
- // }
- // return new JSONObject(jsonStr);
- // }
- public static void main(String[] args) throws JSONException, IOException {
- JSONObject obj = null;
- obj = new JSONObject();
- // obj.put("userName", "213");
- // obj.put("id", 27);
- // JSONArray array = new JSONArray();
- // array.put(obj);
- // obj = new JSONObject();
- // obj.put("userName", "214");
- // obj.put("id", 28);
- // array.put(obj);
- String ostr = "{\"errcode\":0,\"errmsg\":\"ok\",\"userlist\":[{\"userName\":\"卓感科技\",\"id\":\"manager6528\"},{\"userName\":\"程尧\",\"id\":\"03460032393259\"},{\"userName\":\"陈旭东\",\"id\":\"03424335654855\"},{\"userName\":\"董广群\",\"id\":\"03443148156837\"}]}";
- obj = JSONObject.fromObject(ostr);
- System.out.println( obj.get("userlist"));
- JSONArray json = JSONArray.fromObject(obj.get("userlist"));
- List<TSUser> persons = (List<TSUser>)JSONArray.toList(json, TSUser.class);
- System.out.println(persons);
- // Object user = JSONToObj("\"userList\":" + obj.get("userlist").toString(), UserList.class);
- // System.out.println( user);
-
- // JSONObject jsStr = JSONObject.fromObject("{"+obj.get("userlist").toString()+"}");
- // Student stu = (Student) JSONToObj(obj.toString(), Student.class);
- // JSONObject objList = new JSONObject();
- // objList.put("student", array);
- // System.out.println("objList:"+objList);
- // StudentList stuList = (StudentList) JSONToObj(objList.toString(), StudentList.class);
- // System.out.println("student:"+stu);
- // System.out.println("stuList:"+stuList);
- // System.out.println("#####################################");
- // JSONObject getObj = objectToJson(stu);
- // System.out.println(getObj);
- }
- }
|