JSON是由若干个k-v组合的格式,通常用于http请求body,如下就是一个简单的JSON字符串
{ "name": "xiaoming", "id": "1", "users": [ { "name": "xiaoming", "type": "Main", "age": "10" }, { "name": "xiaohong", "type": "Guarator", "age": "20" } ] }
key值都是string类型,value是object类型,可以是string,lsit,int等类型数据
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.9.0</version> </dependency> <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20211205</version> </dependency>
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.47</version> </dependency>
User user1 = User.builder() .age("10") .name("xiaoming") .type(TypeEnum.Main) .build(); User user2 = User.builder() .age("20") .name("xiaohong") .type(TypeEnum.Guarator) .build(); DataDto dataDto = DataDto.builder() .name("xiaoming") .id("1") .users(Arrays.asList(user1,user2)) .build(); System.out.println(dataDto); //对象转换成json,json20211205 JSONObject jsonObject = new JSONObject(dataDto); System.out.println(jsonObject); //json体添加内容 JSONObject res = new JSONObject(); res.put("payload",jsonObject); System.out.println(res); //获取JSON体某个value String define = String.valueOf(res.getJSONObject("payload")); System.out.println(define); //json转换成对象,gson2.9.0 Gson gson = new Gson(); DataDto2 dataDto2 = gson.fromJson(define,DataDto2.class); System.out.println(dataDto2.toString());
//把string转换成JSON JSONObject jsonObject = JSON.parseObject("{\n" + "\t\"name\": \"xiaoming\",\n" + "\t\"id\": \"1\",\n" + "\t\"users\": [\n" + "\t\t{\n" + "\t\t\t\"name\": \"xiaoming\",\n" + "\t\t\t\"type\": \"Main\",\n" + "\t\t\t\"age\": \"10\"\n" + "\t\t},\n" + "\t\t{\n" + "\t\t\t\"name\": \"xiaohong\",\n" + "\t\t\t\"type\": \"Guarator\",\n" + "\t\t\t\"age\": \"20\"\n" + "\t\t}\n" + "\t]\n" + "}"); System.out.println(jsonObject); //json转换成string String jsusers = jsonObject.getString("users"); String jsall =jsonObject.toJSONString(); System.out.println("jsusers:"+jsusers+","+"jsall:"+jsall); //jsonstring转换成对象 DataDto2 dataDto2 = JSON.parseObject(jsonObject.toJSONString(),DataDto2.class); System.out.println(dataDto2.toString());
相同:都可以对象转换成json,json转换成对象;
都可以获取json中某个key值的value值 ;
解析的对象与JSON并不需要完全相同,有匹配的就解析,匹配不到就跳过
不同:fastjson有@JSONField(alternateNames = "users")注解, 可以根据注解替代实体类的变量名来解析;
fastjson是通过反射来解析,需要无参构造函数,同时也需要全参构造函数,有些注解比如@Builder会默认去除@Data的
无参构造函数,此时需要手动添加无参和全参构造函数