采用两种方式json对象的转换com.alibaba和net.sf.json-lib依赖的maven<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.24</version></dependency><dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <version>2.4</version> <classifier>jdk15</classifier></dependency>String json = "{/"name/":/"lil/",/"age/":/"12/",/"address/":'北京',/"obj/":{/"phone/":123131,/"dd/":/"hh/"}}";//net.sf.json方式解析json字符串JSONObject jsonObject = JSONObject.fromObject(json);//直接获取对象name属性String value = jsonObject.getString("name"); //jsonObject中的对象调用对象中的属性 如:json字符串对象中包含obj对象 jsonObject.getJSONObject("obj").get("phone");//com.alibaba方式解析json字符串com.alibaba.fastjson.JSONObject object = com.alibaba.fastjson.JSONObject.parSEObject(json);object.getJSONObject("obj").getString("phone");value = object.getString("age");//将对象转换为json字符串Person person = new Person();person.setName("lis");person.setAge(13);person.setAddress("beijing");String perStr = com.alibaba.fastjson.JSONObject.toJSONString(person);object = com.alibaba.fastjson.JSONObject.parseObject(perStr);//获取Person对象中的address属性value = object.getString("address");List list = Arrays.asList(1, 2, 3);int[] arr = new int[]{3,2,12};//Class<T>指定返回的类型List neList = com.alibaba.fastjson.JSONObject.parseObject(com.alibaba.fastjson.JSONObject.toJSONString(list), List.class);//首先将对象转换为字符串 JSONObject.toJSONStringList<Integer> neArr = (List<Integer>)com.alibaba.fastjson.JSONObject.parseArray(com.alibaba.fastjson.JSONObject.toJSONString(arr),Integer.class);
新闻热点
疑难解答