8种常用json解析示例(原创作者:smallbee 本文转载于:http://smallbee.iteye.com/)

2024-02-27 06:38

本文主要是介绍8种常用json解析示例(原创作者:smallbee 本文转载于:http://smallbee.iteye.com/),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

  1. //转换器  
  2.         GsonBuilder builder = new GsonBuilder();   
  3.         // 不转换没有 @Expose 注解的字段   
  4.         builder.excludeFieldsWithoutExposeAnnotation();  
  5.         Gson gson = builder.create();   
  6.           
  7.         //1、对象转string  
  8.         Student stu = new Student();  
  9.         stu.setStudentId(333);  
  10.         stu.setStudentName("qqq");  
  11.         String stuStr = gson.toJson(stu);  
  12.         System.out.println(stuStr); //{"studentName":"qqq","studentId":333}  
  13.           
  14.           
  15.         //2、string转对象  
  16.         Student user2 = gson.fromJson(stuStr, Student.class);   
  17.         System.out.println(user2);   
  18.         String stuTemp = "{\"studentName\":\"qqq2\",\"studentId\":3335}";  
  19.         Student user4 = gson.fromJson(stuTemp, Student.class);   
  20.         System.out.println(user4);   
  21.   
  22.         //3、对象List转string  
  23.         List<Student> testBeanList = new ArrayList<Student>();   
  24.         Student testBean = new Student();   
  25.         testBean.setStudentId(555);  
  26.         testBean.setStudentName("552");  
  27.         testBeanList.add(testBean);   
  28.           
  29.         //Gson gsonList = new Gson();   
  30.         Type type = new TypeToken<List<Student>>(){}.getType();  //指定集合对象属性  
  31.         String beanListToJson = gson.toJson(testBeanList, type);   
  32.         System.out.println(beanListToJson); //[{"studentName":"552","studentId":555}]   
  33.   
  34.         //集合string转对象list  
  35.         List<Student> testBeanListFromJson = gson.fromJson(beanListToJson, type);   
  36.         System.out.println(testBeanListFromJson); //[555:552]  
  37.   
  38.         //4、集合如果不指定类型 默认为String  
  39.         List<String> testList = new ArrayList<String>();   
  40.         testList.add("first");   
  41.         testList.add("second");   
  42.         String listToJson = gson.toJson(testList);   
  43.         System.out.println(listToJson); //["first","second"]   
  44.           
  45.         //5、集合字符串转回来需要指定类型  
  46.         List<String> testList2 = (List<String>) gson.fromJson(listToJson,   
  47.           new TypeToken<List<String>>() {   
  48.           }.getType());   
  49.         System.out.println(testList2);   
  50.   
  51.         //6、 将HashMap字符串转换为 JSON   
  52.         Map<String, String> testMap = new HashMap<String, String>();   
  53.         testMap.put("id""id.first");   
  54.         testMap.put("name""name.second");   
  55.         String mapToJson = gson.toJson(testMap);   
  56.         System.out.println(mapToJson); //{"id":"id.first","name":"name.second"}  
  57.         //7、stringMap转对象  
  58.         Map<String, String> userMap2 = (Map<String, String>) gson.fromJson(mapToJson,   
  59.                 new TypeToken<Map<String, String>>() {   
  60.             }.getType());   
  61.         System.out.println(userMap2); //{id=id.first, name=name.second}   
  62.   
  63.         //8、对象含有普通对象、集合、map情况  
  64.         Student user1 = new Student();   
  65.         user1.setStudentId(1001);   
  66.         user1.setStudentName("张三");   
  67.           
  68.         Student user3 = new Student();   
  69.         user3.setStudentId(1002);   
  70.         user3.setStudentName("李四");   
  71.           
  72.         Map<String, Student> userMap = new HashMap<String, Student>();   
  73.         userMap.put("user1", user1);   
  74.         userMap.put("user3", user3);   
  75.           
  76.         List<Student> userList = new ArrayList<Student>();   
  77.         userList.add(user1);   
  78.         userList.add(user3);   
  79.           
  80.         Teacher groupBean = new Teacher();   
  81.         groupBean.setStudent(user1);  
  82.         groupBean.setStus(userList);  
  83.         groupBean.setMap((HashMap)userMap);  
  84.         //groupBean.setUserList(userList);   
  85.         Gson gsonGroup = new Gson();   
  86.   
  87.         String sGroupBean = gsonGroup.toJson(groupBean, new TypeToken<Teacher>() {   
  88.             }.getType());   
  89.         System.out.println(sGroupBean);   
  90.         /*{"stus":[{"studentName":"张三","studentId":1001},{"studentName":"李四","studentId":1002}],"student":{"studentName":"张三","studentId":1001},"map":{"user3":{"studentName":"李四","studentId":1002},"user1":{"studentName":"张三","studentId":1001}},"id":0,"age":0}*/  
//转换器GsonBuilder builder = new GsonBuilder(); // 不转换没有 @Expose 注解的字段 builder.excludeFieldsWithoutExposeAnnotation();Gson gson = builder.create(); //1、对象转stringStudent stu = new Student();stu.setStudentId(333);stu.setStudentName("qqq");String stuStr = gson.toJson(stu);System.out.println(stuStr); //{"studentName":"qqq","studentId":333}//2、string转对象Student user2 = gson.fromJson(stuStr, Student.class); System.out.println(user2); String stuTemp = "{\"studentName\":\"qqq2\",\"studentId\":3335}";Student user4 = gson.fromJson(stuTemp, Student.class); System.out.println(user4); //3、对象List转stringList<Student> testBeanList = new ArrayList<Student>(); Student testBean = new Student(); testBean.setStudentId(555);testBean.setStudentName("552");testBeanList.add(testBean); //Gson gsonList = new Gson(); Type type = new TypeToken<List<Student>>(){}.getType();  //指定集合对象属性String beanListToJson = gson.toJson(testBeanList, type); System.out.println(beanListToJson); //[{"studentName":"552","studentId":555}] //集合string转对象listList<Student> testBeanListFromJson = gson.fromJson(beanListToJson, type); System.out.println(testBeanListFromJson); //[555:552]//4、集合如果不指定类型 默认为StringList<String> testList = new ArrayList<String>(); testList.add("first"); testList.add("second"); String listToJson = gson.toJson(testList); System.out.println(listToJson); //["first","second"] //5、集合字符串转回来需要指定类型List<String> testList2 = (List<String>) gson.fromJson(listToJson, new TypeToken<List<String>>() { }.getType()); System.out.println(testList2); //6、 将HashMap字符串转换为 JSON Map<String, String> testMap = new HashMap<String, String>(); testMap.put("id", "id.first"); testMap.put("name", "name.second"); String mapToJson = gson.toJson(testMap); System.out.println(mapToJson); //{"id":"id.first","name":"name.second"}//7、stringMap转对象Map<String, String> userMap2 = (Map<String, String>) gson.fromJson(mapToJson, new TypeToken<Map<String, String>>() { }.getType()); System.out.println(userMap2); //{id=id.first, name=name.second} //8、对象含有普通对象、集合、map情况Student user1 = new Student(); user1.setStudentId(1001); user1.setStudentName("张三"); Student user3 = new Student(); user3.setStudentId(1002); user3.setStudentName("李四"); Map<String, Student> userMap = new HashMap<String, Student>(); userMap.put("user1", user1); userMap.put("user3", user3); List<Student> userList = new ArrayList<Student>(); userList.add(user1); userList.add(user3); Teacher groupBean = new Teacher(); groupBean.setStudent(user1);groupBean.setStus(userList);groupBean.setMap((HashMap)userMap);//groupBean.setUserList(userList); Gson gsonGroup = new Gson(); String sGroupBean = gsonGroup.toJson(groupBean, new TypeToken<Teacher>() { }.getType()); System.out.println(sGroupBean); /*{"stus":[{"studentName":"张三","studentId":1001},{"studentName":"李四","studentId":1002}],"student":{"studentName":"张三","studentId":1001},"map":{"user3":{"studentName":"李四","studentId":1002},"user1":{"studentName":"张三","studentId":1001}},"id":0,"age":0}*/
Java代码   收藏代码
  1. //9、复杂对象string转对象  
  2. Teacher groupBean2 = (Teacher) gson.fromJson(sGroupBean,   
  3.    new TypeToken<Teacher>() {   
  4.    }.getType());   
  5. System.out.println(groupBean2);   
        //9、复杂对象string转对象Teacher groupBean2 = (Teacher) gson.fromJson(sGroupBean, new TypeToken<Teacher>() { }.getType()); System.out.println(groupBean2); 

 

Java代码   收藏代码
  1. package com.andtools;  
  2.   
  3. import com.google.gson.annotations.Expose;  
  4.   
  5. public class Student {  
  6.     @Expose  
  7.     private String studentName;  
  8.     @Expose  
  9.     private int studentId;  
  10.     public Student(){}  
  11.     public Student(int studentId,String studentName){  
  12.         this.setStudentId(studentId);  
  13.         this.setStudentName(studentName);  
  14.     }  
  15.     public String toString(){  
  16.         return this.getStudentId() + ":" + this.getStudentName();  
  17.     }  
  18.     public String getStudentName() {  
  19.         return studentName;  
  20.     }  
  21.     public void setStudentName(String studentName) {  
  22.         this.studentName = studentName;  
  23.     }  
  24.     public int getStudentId() {  
  25.         return studentId;  
  26.     }  
  27.     public void setStudentId(int studentId) {  
  28.         this.studentId = studentId;  
  29.     }  
  30.       
  31. }  
package com.andtools;import com.google.gson.annotations.Expose;public class Student {@Exposeprivate String studentName;@Exposeprivate int studentId;public Student(){}public Student(int studentId,String studentName){this.setStudentId(studentId);this.setStudentName(studentName);}public String toString(){return this.getStudentId() + ":" + this.getStudentName();}public String getStudentName() {return studentName;}public void setStudentName(String studentName) {this.studentName = studentName;}public int getStudentId() {return studentId;}public void setStudentId(int studentId) {this.studentId = studentId;}}

 

Java代码   收藏代码
  1. package com.andtools;  
  2.   
  3. import java.util.HashMap;  
  4. import java.util.List;  
  5. import java.util.Map;  
  6.   
  7. import com.google.gson.annotations.Expose;  
  8.   
  9. public class Teacher {  
  10.     @Expose  
  11.     private int id;  
  12.     @Expose  
  13.     private String name;  
  14.     @Expose  
  15.     private int age;  
  16.     @Expose  
  17.     private Student student;  
  18.     @Expose  
  19.     private List stus;  
  20.     @Expose  
  21.     private HashMap map;  
  22.     public String toString(){  
  23.         return this.getId()+":"+this.getName()+":"+this.getAge() +":"this.getStudent().toString() + ":" + this.getStus() + ":" + this.getMap();  
  24.     }  
  25.     public int getId() {  
  26.         return id;  
  27.     }  
  28.     public void setId(int id) {  
  29.         this.id = id;  
  30.     }  
  31.     public String getName() {  
  32.         return name;  
  33.     }  
  34.     public void setName(String name) {  
  35.         this.name = name;  
  36.     }  
  37.     public int getAge() {  
  38.         return age;  
  39.     }  
  40.     public void setAge(int age) {  
  41.         this.age = age;  
  42.     }  
  43.     public Student getStudent() {  
  44.         return student;  
  45.     }  
  46.     public void setStudent(Student student) {  
  47.         this.student = student;  
  48.     }  
  49.     public List getStus() {  
  50.         return stus;  
  51.     }  
  52.     public void setStus(List stus) {  
  53.         this.stus = stus;  
  54.     }  
  55.     public HashMap getMap() {  
  56.         return map;  
  57.     }  
  58.     public void setMap(HashMap map) {  
  59.         this.map = map;  
  60.     }  
  61.       
  62. }  

这篇关于8种常用json解析示例(原创作者:smallbee 本文转载于:http://smallbee.iteye.com/)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/751510

相关文章

解析 XML 和 INI

XML 1.TinyXML库 TinyXML是一个C++的XML解析库  使用介绍: https://www.cnblogs.com/mythou/archive/2011/11/27/2265169.html    使用的时候,只要把 tinyxml.h、tinystr.h、tinystr.cpp、tinyxml.cpp、tinyxmlerror.cpp、tinyxmlparser.

React+TS前台项目实战(十七)-- 全局常用组件Dropdown封装

文章目录 前言Dropdown组件1. 功能分析2. 代码+详细注释3. 使用方式4. 效果展示 总结 前言 今天这篇主要讲全局Dropdown组件封装,可根据UI设计师要求自定义修改。 Dropdown组件 1. 功能分析 (1)通过position属性,可以控制下拉选项的位置 (2)通过传入width属性, 可以自定义下拉选项的宽度 (3)通过传入classN

tf.split()函数解析

API原型(TensorFlow 1.8.0): tf.split(     value,     num_or_size_splits,     axis=0,     num=None,     name='split' ) 这个函数是用来切割张量的。输入切割的张量和参数,返回切割的结果。  value传入的就是需要切割的张量。  这个函数有两种切割的方式: 以三个维度的张量为例,比如说一

如何在Java中处理JSON数据?

如何在Java中处理JSON数据? 大家好,我是免费搭建查券返利机器人省钱赚佣金就用微赚淘客系统3.0的小编,也是冬天不穿秋裤,天冷也要风度的程序猿!今天我们将探讨在Java中如何处理JSON数据。JSON(JavaScript Object Notation)作为一种轻量级的数据交换格式,在现代应用程序中被广泛使用。Java通过多种库和API提供了处理JSON的能力,我们将深入了解其用法和最佳

帆软报表常用操作

欢迎来到我的博客,代码的世界里,每一行都是一个故事 🎏:你只管努力,剩下的交给时间 🏠 :小破站 帆软报表常用操作 多序号实现使用数据集作为参数空白页或者竖线页修改页面Title金额,或者保留两位小数等等设置日期格式显示图片使用公式 多序号实现 所用函数为SEQ(),如果一张报表中需要用到多个序号,那么就需要加入参数SEQ(1),SEQ(

常用MQ消息中间件Kafka、ZeroMQ和RabbitMQ对比及RabbitMQ详解

1、概述   在现代的分布式系统和实时数据处理领域,消息中间件扮演着关键的角色,用于解决应用程序之间的通信和数据传递的挑战。在众多的消息中间件解决方案中,Kafka、ZeroMQ和RabbitMQ 是备受关注和广泛应用的代表性系统。它们各自具有独特的特点和优势,适用于不同的应用场景和需求。   Kafka 是一个高性能、可扩展的分布式消息队列系统,被设计用于处理大规模的数据流和实时数据传输。它

BD错误集锦7——在集成Spring MVC + MyBtis时使用c3p0作为数据库时报错Method com/mchange/v2/c3p0/impl/NewProxyPreparedStatem

异常信息如下: Type Exception ReportMessage Handler dispatch failed; nested exception is java.lang.AbstractMethodError: Method com/mchange/v2/c3p0/impl/NewProxyPreparedStatement.isClosed()Z is abstractDescr

53、Flink Interval Join 代码示例

1、概述 interval Join 默认会根据 keyBy 的条件进行 Join 此时为 Inner Join; interval Join 算子的水位线会取两条流中水位线的最小值; interval Join 迟到数据的判定是以 interval Join 算子的水位线为基准; interval Join 可以分别输出两条流中迟到的数据-[sideOutputLeftLateData,

陀螺仪LSM6DSV16X与AI集成(8)----MotionFX库解析空间坐标

陀螺仪LSM6DSV16X与AI集成.8--MotionFX库解析空间坐标 概述视频教学样品申请源码下载开启CRC串口设置开启X-CUBE-MEMS1设置加速度和角速度量程速率选择设置FIFO速率设置FIFO时间戳批处理速率配置过滤链初始化定义MotionFX文件卡尔曼滤波算法主程序执行流程lsm6dsv16x_motion_fx_determin欧拉角简介演示 概述 本文将探讨

【文末附gpt升级秘笈】腾讯元宝AI搜索解析能力升级:千万字超长文处理的新里程碑

腾讯元宝AI搜索解析能力升级:千万字超长文处理的新里程碑 一、引言 随着人工智能技术的飞速发展,自然语言处理(NLP)和机器学习(ML)在各行各业的应用日益广泛。其中,AI搜索解析能力作为信息检索和知识抽取的核心技术,受到了广泛的关注和研究。腾讯作为互联网行业的领军企业,其在AI领域的探索和创新一直走在前列。近日,腾讯旗下的AI大模型应用——腾讯元宝,迎来了1.1.7版本的升级,新版本在AI搜