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的定义: 一种轻量级的数据交换格式,具有良好的可读和便于快速编写的特性.业内主流技术为其提供了完整的解决方案(有点类似于正则表达式 ,获得了当今大部分语言的支持),从而可以在不同平台间进行数据 ...
随机推荐
- 2018-2-13-win10-uwp-自定义控件-SplitViewItem
title author date CreateTime categories win10 uwp 自定义控件 SplitViewItem lindexi 2018-2-13 17:23:3 +080 ...
- SAP Adobe Form 教程二 表
本文将介绍一些进阶内容,前文:SAP Adobe Form 教程一 简单示例 方法和对比 使用表对象(Table Object)创建表 优点: 它简单易行. 当我们只有很少的字段单行时,我们可以使用它 ...
- spire.Doc -Index was out of the range
一直以来用的好好的,突然有一天出现:Index was out of the range ED04211_邵武市易逸行软件技术服务有限公司(万顺出行)_其他 升级后问题: 1.合并单元格出现问题 ...
- 01、Java 安全-反序列化基础
Java 反序列化基础 1.ObjectOutputStream 与 ObjectInputStream类 1.1.ObjectOutputStream类 java.io.ObjectOutputSt ...
- Ubuntu 安装谷歌中文输入法
Ubuntu 安装谷歌中文输入法 下载谷歌拼音:sudo apt-get install fcitx-googlepinyin 点击设置: 第一次打开需要点击安装: 设置完成后重启系统 点击右上角键盘 ...
- vue路由跳转的三种方式
目录 1.router-link [实现跳转最简单的方法] 2.this.$router.push({ path:'/user'}) 3.this.$router.replace{path:'/' } ...
- 04.2 go-admin前后端打包为一个服务上线
目录 一.思路: 二.打包go-admin-ui为静态文件 a.修改配置文件 b.打包 c.复制dist到go-admin的static目录里 三.配置go-admin a.配置路由 b.访问页面 视 ...
- gin-vue-admin开发教程 01安装与启用
目录 目标 视频教程地址: 环境要求 前端环境安装文档: 安装node npm cnpm yarn(选装) 后端环境安装文档: Golang1.14.2 环境的安装 goland的配置 gin-vue ...
- fastposter发布1.4.3 跨语言的海报生成器
fastposter发布1.4.3 跨语言的海报生成器 v1.4.3 增加golang语言支持,优化生成器代码,完善官方文档 昨天喝了点小9️⃣,发版慢了些. future: 增加golang语言支持 ...
- three.js介绍和学习资料说明
1.three.js能做什么 Three.js是基于原生WebGL封装运行的三维引擎,在所有WebGL引擎中,Three.js是国内文资料最多.使用最广泛的三维引擎.既然Threejs是一款WebGL ...