目录
1、JSON是一种取代XML的数据结构
2、那么,JSON到底是什么?
3、jackson框架和json-lib框架
3.1、jackson【ObjectMapper】
3.2 、JSONObject和JSONArray
3.3、JSON.parseObject 和 JSON.toJSONString
1、JSON是一种取代XML的数据结构
和xml相比,它更小巧但描述能力却不差,由于它的小巧所以网络传输数据将减少更多流量从而加快速度
2、那么,JSON到底是什么?
JSON就是一串字符串 只不过元素会使用特定的符号标注。
{} 大括号表示对象
[] 中括号表示数组
"" 双引号内是属性或值
: 冒号表示后者是前者的值(这个值可以是字符串、数字也可以是另一个数组或对象)
所以 {"name": "Michael"} 可以理解为是一个包含name为Michael的对象
而 [{"name": "Michael"},{"name": "Jerry"}] 就表示包含两个对象的数组
当然了,你也可以使用 {"name":["Michael","Jerry"]} 来简化上面,这是一个拥有一个name数组的对象
3、jackson框架和json-lib框架
jackson 框架:提供了JsonGenerator 和ObjectMapper两个类,通过这两个类提供的方法可以将java 对象转化为json 对象,json 数组格式,也可以将json对象、数组格式转化为java对象。
json-lib框架:也可以进行json格式和java 对象之间的相互转化,json-lib提供的类主要有:JSONObject ,JSONArray
JSON
3.1、jackson【ObjectMapper】
jsckson实现json与对象,集合,map间的转换
jackson主要用来把对象转为一个json字符串返回到前端,或者把json字符串转为对象。现在大部分数据交换都是以json来传输的。加上现在es的使用越来越多,该类还是很重要的。
注意包名 import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
package java8.test; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import java.util.Arrays; import java.util.List; import java.util.Map; / * @version 1.0 / public class Test4 { public static void main(String[] args) throws Exception { / * 将map转换成json字符串 / Map<String, Object> map = Maps.newHashMap(); map.put("name","张三"); map.put("age",23); //map: {name=张三, age=23} System.out.println("map: "+map); ObjectMapper objectMapper = new ObjectMapper(); String jsonString = objectMapper.writeValueAsString(map); //jsonString: {"name":"张三","age":23} System.out.println("jsonString: "+ jsonString); / * json字符串转换成map对象 / String string = "{\"name\":\"张三\",\"age\":23}"; //string: {"name":"张三","age":23} System.out.println("string: "+string); Map map1 = objectMapper.readValue(string,Map.class); //map1: {name=张三, age=23} System.out.println("map1: "+map1); / * 将对象转换成json字符串 / Person person = new Person("张三",23,"北京"); String string1 = objectMapper.writeValueAsString(person); //{"name":"张三","age":23,"city":"北京"} System.out.println(string1); / * 将json字符串转换为对象 * Person [name=张三, age=23, addr=北京] * @throws Exception */ String string2 = "{\"name\":\"张三\",\"age\":23,\"city\":\"北京\"}"; Person person1 = objectMapper.readValue(string2,Person.class); //Person(name=张三, age=23, city=北京) System.out.println(person1); / * 将数组转换成json字符串 * @throws Exception */ Person p1 = new Person("张三",23,"北京"); Person p2 = new Person("李四",24,"北京"); Person p3 = new Person("王五",25,"北京"); Person[] persones = {p1,p2,p3}; String string3 = objectMapper.writeValueAsString(persones); //[{"name":"张三","age":23,"city":"北京"},{"name":"李四","age":24,"city":"北京"},{"name":"王五","age":25,"city":"北京"}] System.out.println(string3); / * 将json字符串转换成数组 */ String str = "[{\"city\":\"北京\",\"age\":23,\"name\":\"张三\"},{\"city\":\"北京\",\"age\":24,\"name\":\"李四\"},{\"city\":\"北京\",\"age\":25,\"name\":\"王五\"}]"; Person[] persons = objectMapper.readValue(str, new TypeReference<Person[]>(){}); //[Person(name=张三, age=23, city=北京), Person(name=李四, age=24, city=北京), Person(name=王五, age=25, city=北京)] System.out.println(Arrays.toString(persons)); / * 将集合转换成json字符串 */ List list = Lists.newArrayList(); list.add(new Person("张三",23,"北京")); list.add(new Person("李四",24,"北京")); list.add(new Person("王五",25,"北京")); String string5 = objectMapper.writeValueAsString(list); //[{"name":"张三","age":23,"city":"北京"},{"name":"李四","age":24,"city":"北京"},{"name":"王五","age":25,"city":"北京"}] System.out.println(string5); / * 将json字符串转换成集合 */ String string6 = "[{\"city\":\"北京\",\"age\":23,\"name\":\"张三\"},{\"city\":\"北京\",\"age\":24,\"name\":\"李四\"},{\"city\":\"北京\",\"age\":25,\"name\":\"王五\"}]"; List list1 = objectMapper.readValue(string6,new TypeReference<List<Person>>(){}); //[Person(name=张三, age=23, city=北京), Person(name=李四, age=24, city=北京), Person(name=王五, age=25, city=北京)] System.out.println(list1); / * map转json */ Map<String, Object> map2 = Maps.newHashMap(); map2.put("data",list); map2.put("message","传输数据"); String string7 = objectMapper.writeValueAsString(map2); //{"data":[{"name":"张三","age":23,"city":"北京"},{"name":"李四","age":24,"city":"北京"},{"name":"王五","age":25,"city":"北京"}],"message":"传输数据"} System.out.println(string7); / *json转map */ String string8 = "{\"message\":\"传输数据\",\"data\":[{\"name\":\"张三\",\"age\":23,\"city\":\"北京\"},{\"name\":\"李四\",\"age\":24,\"city\":\"北京\"},{\"name\":\"王五\",\"age\":25,\"city\":\"北京\"}]}"; Map readValue = objectMapper.readValue(string8,Map.class); List list3 = (List) readValue.get("data"); System.out.println(list3); } }
讯享网
参考:https://www.cnblogs.com/del88/p/13098678.html
3.2 、JSONObject和JSONArray
1、识别json格式字符串是JSONObject还是JSONArray
JSON数据格式只有两种形式,分别是:
| 1 2 |
|
JSONObject可以用key取值,JSONArray只能遍历取值
2、遍历json数组
假设我们得到的json字符串result如下:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
可以看出来,最外面是个json对象,photos节点是个数组,遍历代码如下:
讯享网import net.sf.json.JSONArray; import net.sf.json.JSONObject public class Test4 { public static void main(String[] args) throws Exception { JSONObject jsonObject = JSONObject.fromObject(result); String feature = jsonObject.getString( "feature" ); JSONArray photoArray = jsonObject.getJSONArray( "photos" ); for ( int i = 0 ; i < photoArray.size(); i++) { JSONObject object = (JSONObject) photoArray.get(i); int id = object.getInt( "id" ); String name = object.getString( "name" ); } }
3.3、JSON.parseObject 和 JSON.toJSONString
JSON.parseObject:将Json字符串转化为相应的对象
JSON.toJSONStrin:将对象转化为Json字符串。
在前后台的传输过程中,Json字符串是相当常用的
首先用maven引入fastjson
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.wujiang.test</groupId> <artifactId>test</artifactId> <version>1.0-SNAPSHOT</version> <properties> <fastjson_version>1.2.28</fastjson_version> </properties> <dependencies> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>${fastjson_version}</version> </dependency> </dependencies> </project>
定义一个model类,员工,有四个属性,如下所示:
讯享网package jsonTest; import java.util.Date; / * @author wujiang * @version 1.0.0. * @date 2017/4/30 */ public class Staff { private String name; private Integer age; private String sex; private Date birthday; //省略getter和setter方法 @Override public String toString() { return "Staff{" + "name='" + name + '\'' + ", age=" + age + ", sex='" + sex + '\'' + ", birthday=" + birthday + '}'; } }
好的,下一步,测试一下JSON.parseObject 和 JSON.toJSONString方法。这里故意在Json字符串中多了一个telephone,少了一个Staff中的birthday,看看输出的对象会有什么变化
package jsonTest; import com.alibaba.fastjson.JSON; / * @author wujiang * @version 1.0.0. * @date 2017/4/30 */ public class jsonTest { public static void main(String[] args) { / * json字符串转化为对象 */ String jsonString = "{name:'Antony',age:'12',sex:'male',telephone:'88888'}"; Staff staff = JSON.parseObject(jsonString, Staff.class); System.out.println(staff.toString()); / * 对象转化为json字符串 */ String jsonStr = JSON.toJSONString(staff); System.out.println(jsonStr); } }
输出结果
在JSON.parseObject 的时候,会去填充名称相同的属性。对于Json字符串中没有,而model类有的属性,会为null;对于model类没有,而Json字符串有的属性,不做任何处理。
至于 JSON.toJSONString 就不需要多说了,看一下就知道
至于应用场景,比方说,用户登录微信公众号的时候,调用微信官方的restful接口,得到该用户的所有信息的一个Json字符串,然后写一个类(将自己需要的信息封装成一个类)。例如下面的伪代码
讯享网String s = httpRequest.sendGet("https://api.weixin..com/sns/oauth2/access_token","appid=" + appId + "&secret=" + appSecret + "&code=" + code + "&grant_type=authorization_code"); UserAuthorizationReturn userAuthorizationReturn = JSON.parseObject(s, UserAuthorizationReturn.class);
另外注意,如果需要对List进行json的转化,转成json字符串的方式没有区别,但是从json字符串转化回List时,需要使用JSON.parseArray方法
String jsonStr = JSON.toJSONString(tableInfoVO.getFieldInfo()) List<FiledInfoVO> filedInfoVOList = JSON.parseArray(jsonStr,FiledInfoVO.class)
https://blog.csdn.net/beidaol/article/details/
https://blog.csdn.net/dafeige8/article/details/

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/130915.html