Java JSON组成和解析
本框架JSON元素组成和分析,JsonElement分三大类型JsonArray,JsonObject,JsonString。
JsonArray:数组和Collection子类,指定数组的话,使用ArrayList来add元素,遍历ArrayList再使用Array.newInstance生成数组并添加元素即可.
JsonObject:带有泛型的封装类,给带有泛型的字段赋值,关键在于如何根据“指定的类型”和“Field.getGenericType”来生成新的字段Type。
需要你了解java.lang.reflect.Type的子类
java.lang.reflect.GenericArrayType //通用数组类型 T[]
java.lang.reflect.ParameterizedType //参数类型,如: java.util.List<java.lang.String> java.util.Map<java.lang.String,java.lang.Object>
java.lang.reflect.TypeVariable //类型变量 K,V
java.lang.reflect.WildcardType //通配符类,例如: ?, ? extends Number, ? super Integer
java.lang.Class //int.class User.class .....
JsonString:分析字符串并解析成指定的对应类型
下面是本JSON框架的分析图

下面是简陋版的解析代码。该类没有解析日期,数值等代码,只是方便理解解析过程。
package june.zero.json.reader; import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; public class JsonSimpleParser implements CharSequence { public static void main(String[] args) {
String json = "[{a:1,b:2},[1,2,3]]";
Object obj = new JsonSimpleParser().parse(json);
System.out.println(obj);
} protected static final String JSON_EXTRA_CHAR_ERROR = "Extra characters exist! ";
protected static final String JSON_OBJECT_COLON_ERROR = "Wrong format of JsonObject, no separator colon! ";
protected static final String JSON_OBJECT_END_ERROR = "The JsonObject format must end with comma as a separator or with right curly brace! ";
protected static final String JSON_ARRAY_END_ERROR = "The JsonArray format must end with comma as a separator or with right bracket! ";
protected static final String JSON_STRING2_END_ERROR = "The character starts with double quotation marks, but does not end with double quotation marks! ";
protected static final String JSON_STRING1_END_ERROR = "The character starts with single quotation marks, but does not end with single quotation marks! "; protected Reader reader;
protected static final int capacity = 1024;
protected final char[] cache = new char[capacity];
protected int count;
protected int position; public void read() throws IOException {
this.position = 0;
this.count = this.reader.read(this.cache,0,capacity);
} /**
* 当前指针指向的字符
* @return
*/
public char current() {
if(this.count==-1) return '\uffff';
return this.cache[this.position];
}
/**
* 当前指针指向的索引下标
* @return
*/
public int position() {
return this.position;
} /**
* 指针指向下一个字符,判断是否需要重新读取数据
* @return
* @throws IOException
*/
public boolean nextRead() throws IOException {
return ++this.position>=this.count;
} /**
* 指针指向下一个字符
* @return
* @throws IOException
*/
public void next() throws IOException {
if(++this.position>=this.count){
this.position = 0;
this.count = this.reader.read(this.cache,0,capacity);
}
}
/**
* 跳过空白字符
* @throws IOException
*/
public void skip() throws IOException {
while(this.count!=-1&&Character.isWhitespace(this.current())){
if(++this.position>=this.count){
this.position = 0;
this.count = this.reader.read(this.cache,0,capacity);
}
}
} public Object parse(String json) throws RuntimeException {
return parse(new StringReader(json));
} /**
* 解析
*/
public Object parse(Reader reader) throws RuntimeException {
try {
this.reader = reader;
this.read();
Object value = parse();
this.skip();
if(this.count!=-1){
throw new RuntimeException(JSON_EXTRA_CHAR_ERROR);
}
return value;
} catch (Throwable e) {
throw new RuntimeException(e);
} finally {
try {
this.close();
} catch (IOException e) { }
}
} protected Object parse() throws IOException {
this.skip();
char current = this.current();
if(current=='{'){
this.next();
this.skip();
Map<Object, Object> object = new HashMap<Object, Object>();
if(this.current() == '}') {
this.next();
return object;
}
do{
Object key = parse();
this.skip();
if(this.current()!=':'){
throw new RuntimeException(JSON_OBJECT_COLON_ERROR);
}
this.next();
object.put(key, parse());
this.skip();
current = this.current();
if(current=='}') break;
if(current!=','){
throw new RuntimeException(JSON_OBJECT_END_ERROR);
}
this.next();
this.skip();
}while(true);
this.next();
return object;
}
if(current=='['){
this.next();
this.skip();
List<Object> array = new ArrayList<Object>();
if(this.current() == ']'){
this.next();
return array;
}
do{
array.add(parse());
this.skip();
current = this.current();
if(current==']') break;
if(current!=','){
throw new RuntimeException(JSON_ARRAY_END_ERROR);
}
this.next();
this.skip();
}while(true);
this.next();
return array;
}
this.skip();
StringBuilder string = new StringBuilder();
if(current=='"'){
this.next(); int offset = this.position;
while(this.count!=-1&& this.current()!='"'){
if(this.nextRead()){
string.append(this, offset, this.position);
offset = 0;
this.position = 0;
this.count = this.reader.read(this.cache,0,capacity);
}
}
string.append(this, offset, this.position); if(this.current()!='"'){
throw new RuntimeException(JSON_STRING2_END_ERROR);
}
this.next(); return string;
}
if(current=='\''){
if(++this.position>=this.count){
this.position = 0;
this.count = this.reader.read(this.cache,0,capacity);
} int offset = this.position;
while(this.count!=-1&&this.current()!='\''){
if(this.nextRead()){
string.append(this, offset, this.position);
offset = 0;
this.read();
}
}
string.append(this, offset, this.position); if(this.current()!='\''){
throw new RuntimeException(JSON_STRING1_END_ERROR);
}
this.next(); return string;
} int offset = this.position;
while(this.count!=-1&&
(current = this.current())!=','&&
current!=':'&&
current!=']'&&
current!='}'&&
!Character.isWhitespace(current)){
if(this.nextRead()){
string.append(this, offset, this.position);
offset = 0;
this.read();
}
}
string.append(this, offset, this.position);
return string;
} /**
* 关闭流
* @throws IOException
*/
public void close() throws IOException{
if(this.reader!=null){
this.reader.close();
this.reader = null;
}
} @Override
public char charAt(int index) {
return this.cache[index];
}
@Override
public int length() {
return this.count;
}
@Override
public CharSequence subSequence(int start, int end) {
if (start < 0)
throw new StringIndexOutOfBoundsException(start);
if (end > count)
throw new StringIndexOutOfBoundsException(end);
if (start > end)
throw new StringIndexOutOfBoundsException(end - start);
StringBuilder string = new StringBuilder();
for (int i = start; i < end; i++) {
string.append(this.cache[i]);
}
return string;
}
@Override
public String toString() {
if(this.count<0) return null;
return new String(this.cache,this.position,this.count-this.position);
} }
转载请标明该来源。https://www.cnblogs.com/JuneZero/p/18252639
源码和jar包及其案例:https://www.cnblogs.com/JuneZero/p/18237283
Java JSON组成和解析的更多相关文章
- java json 的生成和解析 --json-lib
类(java json的解析和生成): import java.util.HashMap; import java.util.Map; import net.sf.json.JSONArray; im ...
- java JSON的使用和解析
There is no royal road to learning. 博主:JavaPanda https://www.cnblogs.com/LearnAndGet/p/10009646.html ...
- Java中哪个JSON库的解析速度是最快的?
JSON已经成为当前服务器与WEB应用之间数据传输的公认标准,不过正如许多我们所习以为常的事情一样,你会觉得这是理所当然的便不再深入思考 了.我们很少会去想用到的这些JSON库到底有什么不同,但事实上 ...
- android Json Gson FastJson 解析
一 Json xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:a ...
- java -json()
json-lib和org.json的使用几乎是相同的,我总结出的区别有两点: 两种包 1. List集合转换成json方法 List list = new ArrayList(); list.add( ...
- Android 之 json数据的解析(jsonReader)
json数据的解析相对而言,还是比较容易的,实现的代码也十分简单.这里用的是jsonReade方法来进行json数据解析. 1.在解析之前,大家需要知道什么是json数据. json数据存储的对象是无 ...
- JSON 之FastJson解析
http://blog.sina.com.cn/s/blog_7ffb8dd501013qas.html 一.阿里巴巴FastJson是一个Json处理工具包,包括“序列化”和“反序列化”两部分,它具 ...
- iOS开发网络篇-JSON文件的解析
一.什么是JSON数据 1.JSON的简单介绍 JSON:是一种轻量级的传输数据的格式,用于数据的交互 JSON是javascript语言的一个子集.javascript是个脚本语言(不需要编译),用 ...
- (转)JSON 之FastJson解析
一.阿里巴巴FastJson是一个Json处理工具包,包括“序列化”和“反序列化”两部分,它具备如下特征:速度最快,测试表明,fastjson具有极快的性能,超越任其他的Java Json parse ...
- Android Json生成及解析实例
JSON的定义: 一种轻量级的数据交换格式,具有良好的可读和便于快速编写的特性.业内主流技术为其提供了完整的解决方案(有点类似于正则表达式 ,获得了当今大部分语言的支持),从而可以在不同平台间进行数据 ...
随机推荐
- [K8s] Kubernetes核心基础概念 Node, Pod, ReplicaSet, Deployment, Service, Ingress, ConfigMap
Node 即 Kubernetes 集群中的一台工作机器,物理机或者虚拟机. https://kubernetes.io/zh/docs/concepts/architecture/nodes/ 通常 ...
- [ERROR] listen tcp :80: bind: permission denied
出现这类提示的时候,表明当前用户没有权限进行 bind 操作. 在某些 Linux 云服务器提供商的运行环境中会出现. 解决方式:使用 sudo 切换为 root,然后在执行原操作. Refer:li ...
- 开发日志:windows 服务器禁用TLS1.0和TLS1.1协议使网站更安全
SSL/TLS 的版本 协议 发布时间 状态 SSL 1.0 未公布 未公布 SSL 2.0 1995 年 已于 2011 年弃用 SSL 3.0 1996 年 已于 2015 年弃用 TLS 1.0 ...
- Solution Set - 矩阵加速
A[HDU2604]求不含子串010和000的,长为\(n\)的01序列数. B[HDU6470]数列\(\{a_n\}:a_1=1,a_2=2,a_n=a_{n-1}+2a_{n-2}+n^3\), ...
- gin返回json假数据
package main import ( "github.com/gin-gonic/gin" "encoding/json" "fmt" ...
- 瑞亚时间管理大师,基于 .NET 6 和 Angular 构建的在线任务管理协作平台
瑞亚时间管理大师 瑞亚时间管理大师, 是一个在线的任务管理.项目管理. 团队协作平台.瑞亚 拥有现代化的页面风格,高效.简便,同时适合个人和团队使用. 瑞亚对个人免费,提供了无限制的任务,列表,和空间 ...
- 在 Chromebook 上使用 Word 的最佳方法
Splashtop 允许您从 Chromebook 远程控制 Windows 和 Mac 计算机,从而可以访问 Word 的桌面版本和所有文件. 对于远程工作者和学生,Chromebook 可以是一种 ...
- C数据结构:KMP算法详解(呕心沥血)
KMP算法 作者心声 了解暴力求解(必需会) KMP算法详解 记住我这段话(你会爱上它的)← : ①前后缀及其用处 ②求出前后缀的next数组 求出next数组的代码 开始实现KMP算法 结尾 附上源 ...
- C语言:将有顺序的数组进行逆序排序
//设计逆向排序之,数字有序排列,进行逆向排序 主要思想就是头和尾进行交换,前提是------数字必须是排好序的才能进行逆序排 /*假设数组为: 7,8,9,10,11 1 N ...
- echarts(数据可视化图表)
echarts饼图详细 echarts下载 https://echarts.apache.org/zh/index.html echarts官网 http://www.isqqw.com/#/hom ...