JSON案例
原文链接:https://zhuanlan.zhihu.com/p/62763428
json字符串->JSONObject
用JSON.parseObject()方法即可将JSon字符串转化为JSON对象,利用JSONObject中的get()方法来获取JSONObject中的相对应的键对应的值
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.jiyong.config.Student;
import com.jiyong.config.Teacher;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Fastjson用法
*/
public class FastJsonOper {
//json字符串-简单对象型,加\转义
private static final String JSON_OBJ_STR = "{\"studentName\":\"lily\",\"studentAge\":12}";
//json字符串-数组类型
private static final String JSON_ARRAY_STR = " [{\"studentName\":\"lily\",\"studentAge\":12}," +
"{\"studentName\":\"lucy\",\"studentAge\":15}]";
//复杂格式json字符串
private static final String COMPLEX_JSON_STR = "{\"teacherName\":\"crystall\"," +
"\"teacherAge\":27,\"course\":{\"courseName\":\"english\",\"code\":1270},\"students\":[{\"studentName\":\"lily\",\"studentAge\":12},{\"studentName\":\"lucy\",\"studentAge\":15}]}";
// json字符串与JSONObject之间的转换
@Test
public void JsonStrToJSONObject(){ JSONObject jsonObject = JSON.parseObject(JSON_OBJ_STR);
System.out.println("StudentName: " + jsonObject.getString("studentName") + "," + "StudentAge: " + jsonObject.getInteger("studentAge"));
}
}
JSONObject->json字符串
用JSON.toJSONString()方法即可将JSON对象转化为JSON字符串
/**
* 将JSONObject转换为JSON字符串,用JSON.toJSONString()方法即可将JSON字符串转化为JSON对象
*/
@Test
public void JSONObjectToJSONString(){
JSONObject jsonObject = JSON.parseObject(JSON_OBJ_STR);
String s = JSON.toJSONString(jsonObject);
System.out.println(s);
}
JSON字符串数组->JSONArray
将JSON字符串数组转化为JSONArray,通过JSON的parseArray()方法。JSONArray本质上还是一个数组,对其进行遍历取得其中的JSONObject,然后再利用JSONObject的get()方法取得其中的值。有两种方式进行遍历
- 方式一:通过jsonArray.size()获取JSONArray中元素的个数,再通过getJSONObject(index)获取相应位置的JSONObject,循环变量取得JSONArray中的JSONObject,再利用JSONObject的get()进行取值。
- 方式二:通过jsonArray.iterator()获取迭代器
/**
* 将JSON字符串数组转化为JSONArray,通过JSON的parseArray()方法
*/
@Test
public void JSONArrayToJSONStr(){
JSONArray jsonArray = JSON.parseArray(JSON_ARRAY_STR);
/**
* JSONArray本质上还是一个数组,对其进行遍历取得其中的JSONObject,然后再利用JSONObject的get()方法取得其中的值
* 方式一是通过jsonArray.size()获取JSONArray中元素的个数,
* 再通过getJSONObject(index)获取相应位置的JSONObject,在利用JSONObject的get()进行取值
* 方式二是通过jsonArray.iterator()获取迭代器
*
*/
// 遍历方式一
// int size = jsonArray.size();
// for(int i = 0;i < size;i++){
// JSONObject jsonObject = jsonArray.getJSONObject(i);
// System.out.println("studentName: " + jsonObject.getString("studentName") + ",StudentAge: " + jsonObject.getInteger("studentAge"));
// }
// 遍历方式二
Iterator<Object> iterator = jsonArray.iterator();
while (iterator.hasNext()){
JSONObject jsonObject = (JSONObject) iterator.next();
System.out.println("studentName: " + jsonObject.getString("studentName") + ",StudentAge: " + jsonObject.getInteger("studentAge"));
}
}
JSONArray->json字符串
用JSON.toJSONString()方法即可将JSONArray转化为JSON字符串
/**
* JSONArray到json字符串-数组类型的转换
*/
@Test
public void JSONArrayToJSONString(){
JSONArray jsonArray = JSON.parseArray(JSON_ARRAY_STR);
String s = JSON.toJSONString(jsonArray);
System.out.println(s);
}
复杂JSON格式字符串->JSONObject
将复杂JSON格式字符串转换为JSONObject,也是通过JSON.parseObject()
/**
* 将复杂JSON格式字符串转换为JSONObject,也是通过JSON.parseObject(),可以取其中的部分
*/
@Test
public void JSONStringTOJSONObject(){
JSONObject jsonObject = JSON.parseObject(COMPLEX_JSON_STR);
// 获取简单对象
String teacherName = jsonObject.getString("teacherName");
Integer teacherAge = jsonObject.getInteger("teacherAge");
System.out.println("teacherName: " + teacherName + ",teacherAge " + teacherAge);
// 获取JSONObject对象
JSONObject course = jsonObject.getJSONObject("course");
// 获取JSONObject中的数据
String courseName = course.getString("courseName");
Integer code = course.getInteger("code");
System.out.println("courseName: " + courseName + " code: " + code);
// 获取JSONArray对象
JSONArray students = jsonObject.getJSONArray("students");
// 获取JSONArray的中的数据
Iterator<Object> iterator = students.iterator();
while (iterator.hasNext()){
JSONObject jsonObject1 = (JSONObject) iterator.next();
System.out.println("studentName: " + jsonObject1.getString("studentName") + ",StudentAge: "
+ jsonObject1.getInteger("studentAge"));
}
}
复杂JSONObject->json字符串
用JSON.toJSONString()方法即可将复杂JSONObject转化为JSON字符串
/**
* 复杂JSONObject到json字符串的转换
*/
@Test
public void JSONObjectTOJSON(){
JSONObject jsonObject = JSON.parseObject(COMPLEX_JSON_STR);
String s = JSON.toJSONString(jsonObject);
System.out.println(s);
}
json字符串->JavaBean
定义JavaBean类
package com.fastjson;
public class Student {
private String studentName;
private int studentAge;
public Student() {
}
public Student(String studentName, int studentAge) {
this.studentName = studentName;
this.studentAge = studentAge;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public int getStudentAge() {
return studentAge;
}
public void setStudentAge(int studentAge) {
this.studentAge = studentAge;
}
@Override
public String toString() {
return "Student{" +
"studentName='" + studentName + '\'' +
", studentAge=" + studentAge +
'}';
}
} package com.jiyong.config;
/**
* 对于复杂嵌套的JSON格式,利用JavaBean进行转换的时候要注意
* 1、有几个JSONObject就定义几个JavaBean
* 2、内层的JSONObject对应的JavaBean作为外层JSONObject对应的JavaBean的一个属性
* 3、解析方法有两种
* 第一种方式,使用TypeReference<T>类
* Teacher teacher = JSONObject.parseObject(COMPLEX_JSON_STR, new TypeReference<Teacher>() {})
* 第二种方式,使用Gson思想
* Teacher teacher = JSONObject.parseObject(COMPLEX_JSON_STR, Teacher.class);
*/
import java.util.List;
public class Teacher {
private String teacherName;
private int teacherAge;
private Course course;
private List<Student> students;
public Teacher() {
}
public Teacher(String teacherName, int teacherAge, Course course, List<Student> students) {
this.teacherName = teacherName;
this.teacherAge = teacherAge;
this.course = course;
this.students = students;
}
public String getTeacherName() {
return teacherName;
}
public void setTeacherName(String teacherName) {
this.teacherName = teacherName;
}
public int getTeacherAge() {
return teacherAge;
}
public void setTeacherAge(int teacherAge) {
this.teacherAge = teacherAge;
}
public Course getCourse() {
return course;
}
public void setCourse(Course course) {
this.course = course;
}
public List<Student> getStudents() {
return students;
}
public void setStudents(List<Student> students) {
this.students = students;
}
@Override
public String toString() {
return "Teacher{" +
"teacherName='" + teacherName + '\'' +
", teacherAge=" + teacherAge +
", course=" + course +
", students=" + students +
'}';
}
} package com.jiyong.config;
public class Course {
private String courseName;
private int code;
public Course() {
}
public Course(String courseName, int code) {
this.courseName = courseName;
this.code = code;
}
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
@Override
public String toString() {
return "Course{" +
"courseName='" + courseName + '\'' +
", code=" + code +
'}';
}
}
Jason字符串转换为JavaBean有三种方式,推荐通过反射的方式。
/**
* json字符串-简单对象到JavaBean之间的转换
* 1、定义JavaBean对象
* 2、Jason字符串转换为JavaBean有三种方式,推荐通过反射的方式
*/
@Test
public void JSONStringToJavaBeanObj(){
// 第一种方式
JSONObject jsonObject = JSON.parseObject(JSON_OBJ_STR);
String studentName = jsonObject.getString("studentName");
Integer studentAge = jsonObject.getInteger("studentAge");
Student student = new Student(studentName, studentAge);
// 第二种方式,//第二种方式,使用TypeReference<T>类,由于其构造方法使用protected进行修饰,故创建其子类
Student student1 = JSON.parseObject(JSON_OBJ_STR, new TypeReference<Student>() {});
// 第三种方式,通过反射,建议这种方式
Student student2 = JSON.parseObject(JSON_OBJ_STR, Student.class);
}
JavaBean ->json字符串
也是通过JSON的toJSONString,不管是JSONObject、JSONArray还是JavaBean转为为JSON字符串都是通过JSON的toJSONString方法。
/**
* JavaBean转换为Json字符串,也是通过JSON的toJSONString,不管是JSONObject、JSONArray还是JavaBean转为为JSON字符串都是通过JSON的toJSONString方法
*/
@Test
public void JavaBeanToJsonString(){
Student lily = new Student("lily", );
String s = JSON.toJSONString(lily);
System.out.println(s);
}
json字符串数组->JavaBean-List
/**
* json字符串-数组类型到JavaBean_List的转换
*/
@Test
public void JSONStrToJavaBeanList(){
// 方式一:
JSONArray jsonArray = JSON.parseArray(JSON_ARRAY_STR);
//遍历JSONArray
List<Student> students = new ArrayList<Student>();
Iterator<Object> iterator = jsonArray.iterator();
while (iterator.hasNext()){
JSONObject next = (JSONObject) iterator.next();
String studentName = next.getString("studentName");
Integer studentAge = next.getInteger("studentAge");
Student student = new Student(studentName, studentAge);
students.add(student);
}
// 方式二,使用TypeReference<T>类,由于其构造方法使用protected进行修饰,故创建其子类
List<Student> studentList = JSON.parseObject(JSON_ARRAY_STR,new TypeReference<ArrayList<Student>>() {});
// 方式三,使用反射
List<Student> students1 = JSON.parseArray(JSON_ARRAY_STR, Student.class);
System.out.println(students1);
}
JavaBean-List ->json字符串数组
/**
* JavaBean_List到json字符串-数组类型的转换,直接调用JSON.toJSONString()方法即可
*/
@Test
public void JavaBeanListToJSONStr(){
Student student = new Student("lily", );
Student student1 = new Student("lucy", );
List<Student> students = new ArrayList<Student>();
students.add(student);
students.add(student1);
String s = JSON.toJSONString(student);
System.out.println(s);
}
复杂嵌套json格式字符串->JavaBean_obj
对于复杂嵌套的JSON格式,利用JavaBean进行转换的时候要注意:
- 有几个JSONObject就定义几个JavaBean
- 内层的JSONObject对应的JavaBean作为外层JSONObject对应的JavaBean的一个属性
/**
* 复杂json格式字符串到JavaBean_obj的转换
*/
@Test
public void ComplexJsonStrToJavaBean(){
//第一种方式,使用TypeReference<T>类,由于其构造方法使用protected进行修饰,故创建其子类
Teacher teacher = JSON.parseObject(COMPLEX_JSON_STR, new TypeReference<Teacher>() {});
// 第二种方式,使用反射
Teacher teacher1 = JSON.parseObject(COMPLEX_JSON_STR, Teacher.class);
}
JavaBean_obj->复杂json格式字符串
/**
* 复杂JavaBean_obj到json格式字符串的转换
*/
@Test
public void JavaBeanToComplexJSONStr(){
Teacher teacher = JSON.parseObject(COMPLEX_JSON_STR, Teacher.class);
String s = JSON.toJSONString(teacher);
System.out.println(s);
}
JSON案例的更多相关文章
- Ajax&Json案例
案例: * 校验用户名是否存在 1. 服务器响应的数据,在客户端使用时,要想当做json数据格式使用.有两种解决方案: 1. $.get(type):将最后一个参数type指定为"json& ...
- Android 使用Gson解析json案例具体解释
一.眼下解析json有三种工具:org.json(Java经常使用的解析),fastjson(阿里巴巴project师开发的),Gson(Google官网出的),解析速度最快的是Gson,下载地址:h ...
- 爬虫之JSON案例
糗事百科实例: 爬取糗事百科段子,假设页面的URL是 http://www.qiushibaike.com/8hr/page/1 要求: 使用requests获取页面信息,用XPath / re 做数 ...
- json格式化显示样式js代码分享
最近开发中需要在页面展示json.特整理了下代码,送给大家,希望能帮到有同样需求的朋友们. 代码: <html> <script src="http://cdn.bootc ...
- ASP.NET与json对象互转
这两天写这个xml跟json的读写,心累啊,也不是很理解,请大家多指教 首先来个热身菜做一个简单的解析json 在script里写一个简单的弹窗效果 <script> //script里简 ...
- python字典保存至json文件
import os import json class SaveJson(object): def save_file(self, path, item): # 先将字典对象转化为可写入文本的字符串 ...
- 常见Serialize技术探秘(ObjectXXStream、XML、JSON、JDBC byte编码、Protobuf)
目前业界有各种各样的网络输出传输时的序列化和反序列化方案,它们在技术上的实现的初衷和背景有较大的区别,因此在设计的架构也会有很大的区别,最终在落地后的:解析速度.对系统的影响.传输数据的大小.可维护性 ...
- odoo controllers 中type="Json" 或type="http"
服务端接收参考: # 导包 from odoo import http class HttpRequest(http.Controller): @http.route('/url', type='js ...
- 零基础学习java------35---------删除一个商品案例,删除多个商品,编辑(修改商品信息),校验用户名是否已经注册(ajax)
一. 删除一个商品案例 将要操作的表格 思路图 前端代码 <%@ page language="java" contentType="text/html; cha ...
随机推荐
- 统计元音(hdu20)
输入格式:输入一个整型,再循环输入带空格的字符串. 思考:先用scanf()函数输入一个整型,后面直接来个大循环,带空格字符串输入直接用gets()函数. 注意:由于scanf()里面多加了%c,&a ...
- Spring全家桶——SpringBoot渐入佳境
Spring全家桶系列--SpringBoot渐入佳境 萌新:小哥,我在实体类写了那么多get/set方法,看着很迷茫 小哥:那不是可以自动生成吗? 萌新:虽然可以自动生成,但是如果我要修改某个变量的 ...
- Algorithms - Data Structure - Perfect Hashing - 完全散列
相关概念 散列表 hashtable 是一种实现字典操作的有效数据结构. 在散列表中,不是直接把关键字作为数组的下标,而是根据关键字计算出相应的下标. 散列函数 hashfunction'h' 除法散 ...
- 【谎言大揭秘】Modin真的比pandas运行更快吗?
最近看了某公众号文章,推荐了所谓的神器,据说读取速度吊打pandas,可谓牛逼,事实真是这样吗? 来一起揭秘真相. 首先安装包. # pip install ray # pip install das ...
- mybatis是怎样炼成的
前言 一些个人感受:不管分析什么源码,如果我们能摸索出作者的心路历程,跟着他的脚步一步一步往前走,这样才能接近事实的真相,也能更平滑更有趣的学习到知识.跟福尔摩斯探案一样,作者都经历了些什么,为什么他 ...
- 【JUC】CountDownLatch和Java枚举的使用例子
public enum CountryEnum { ONE(1,"春"), TWO(2,"夏"), THREE(3,"秋"), FOUR(4 ...
- 前端基础进阶(十五):详解 ES6 Modules
对于新人朋友来说,想要自己去搞定一个ES6开发环境并不是一件容易的事情,因为构建工具的学习本身又是一个非常大的方向,我们需要花费不少的时间才能掌握它. 好在慢慢的开始有大神提供了一些非常简单易懂,学习 ...
- [Firefox附加组件]0001.入门
Firefox 火狐浏览器,拥有最快.最安全的上网体验,并且火狐拥有超过一万个的 扩展(add-ons),提供各种不同的扩展功能,您可以简单的下载.安装这些扩展以增强您的火狐功能,帮助您更好.更个性化 ...
- html5学习之路_002
html块 html块元素 块元素在显示时,通常会以新行开始 如:<h1>.<p>.<ul> html内联元素 内联元素头通常不会以新行开始 如:<b> ...
- JavaScript——闭包(转自别人)
有这样一个段子:说闭包的主要作用是什么?,答:面试.确实在许多面试中,闭包是必问项目,所以不为别的,只为面试,理解闭包就很重要. 说到 闭包 ,这是js不得不提的一个特性,很多传统语言都不具备这样的特 ...