本框架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组成和解析的更多相关文章

  1. java json 的生成和解析 --json-lib

    类(java json的解析和生成): import java.util.HashMap; import java.util.Map; import net.sf.json.JSONArray; im ...

  2. java JSON的使用和解析

    There is no royal road to learning. 博主:JavaPanda https://www.cnblogs.com/LearnAndGet/p/10009646.html ...

  3. Java中哪个JSON库的解析速度是最快的?

    JSON已经成为当前服务器与WEB应用之间数据传输的公认标准,不过正如许多我们所习以为常的事情一样,你会觉得这是理所当然的便不再深入思考 了.我们很少会去想用到的这些JSON库到底有什么不同,但事实上 ...

  4. android Json Gson FastJson 解析

    一 Json xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:a ...

  5. java -json()

    json-lib和org.json的使用几乎是相同的,我总结出的区别有两点: 两种包 1. List集合转换成json方法 List list = new ArrayList(); list.add( ...

  6. Android 之 json数据的解析(jsonReader)

    json数据的解析相对而言,还是比较容易的,实现的代码也十分简单.这里用的是jsonReade方法来进行json数据解析. 1.在解析之前,大家需要知道什么是json数据. json数据存储的对象是无 ...

  7. JSON 之FastJson解析

    http://blog.sina.com.cn/s/blog_7ffb8dd501013qas.html 一.阿里巴巴FastJson是一个Json处理工具包,包括“序列化”和“反序列化”两部分,它具 ...

  8. iOS开发网络篇-JSON文件的解析

    一.什么是JSON数据 1.JSON的简单介绍 JSON:是一种轻量级的传输数据的格式,用于数据的交互 JSON是javascript语言的一个子集.javascript是个脚本语言(不需要编译),用 ...

  9. (转)JSON 之FastJson解析

    一.阿里巴巴FastJson是一个Json处理工具包,包括“序列化”和“反序列化”两部分,它具备如下特征:速度最快,测试表明,fastjson具有极快的性能,超越任其他的Java Json parse ...

  10. Android Json生成及解析实例

    JSON的定义: 一种轻量级的数据交换格式,具有良好的可读和便于快速编写的特性.业内主流技术为其提供了完整的解决方案(有点类似于正则表达式 ,获得了当今大部分语言的支持),从而可以在不同平台间进行数据 ...

随机推荐

  1. 如何基于Dataphin实现敏感数据保护

    ​简介: 在企业的发展过程中,如果不重视敏感数据的保护,和数据安全体系的建设,那么一旦发生了敏感数据泄漏事件,轻则企业口碑受损,业务受影响:重则会直接触法律,受到主管部门的处罚和制裁.本文将以一个最常 ...

  2. WPF开源轻便、快速的桌面启动器

    前言 今天大姚给大家分享一款WPF开源.简单.轻便.快速的桌面启动器(支持多主题.多语言:简体中文.繁体中文.英文等):CurvaLauncher. WPF介绍 WPF 是一个强大的桌面应用程序框架, ...

  3. [GPT] gradio-chatbot 原理及代码解析

      GradioChatBot 是一个基于 Gradio 的聊天机器人,它可以与不同的 URL 进行对话.其原理是通过将用户输入的文本发送到指定的 URL,然后接收并解析 URL 返回的响应,然后将响 ...

  4. Istio微服务入门---通过istio部署微服务实现灰度发布(15)

    一.Istio简介 1.1 Istio介绍 官方文档:https://istio.io/docs/concepts/what-is-istio/ 中文官方文档:https://istio.io/zh/ ...

  5. 一个库帮你轻松的创建漂亮的.NET控制台应用程序

    前言 做过.NET控制台应用程序的同学应该都知道原生的.NET控制台应用程序输出的内容都比较的单调,假如要编写漂亮且美观的控制台输出内容或者样式可能需要花费不少的时间去编写代码和调试.今天大姚给大家分 ...

  6. 【2023知乎爬虫】我用Python爬虫爬了2386条知乎评论!

    目录 一.爬取目标 二.展示爬取结果 三.爬虫代码讲解 3.1 分析知乎页面 3.2 爬虫代码 四.同步视频 五.完整源码 您好,我是 @马哥python说,一枚10年程序猿. 一.爬取目标 前些天我 ...

  7. 简说Python之面向对象

    目录 Python对象 对象的内置方法 __init__方法 __str__方法 对象的多态 对象的封装 对象的继承 之前介绍了函数.对象代表了什么.可以称为"一篮子"计划,把数据 ...

  8. python教程8-页面爬虫

    python爬虫常用requests和beautifulSoup这2个第三方模块.需要先进行手动安装. requests负责下载页面数据,beautifulSoup负责解析页面标签. 关于beauti ...

  9. windows server2012 挂载linux的nfs共享目录

    1.安装NFS客户端 首先win-server上添加角色-----选择文件服务-----网络文件系统(或者NFS客户端)-安装 2.挂载nfs目录 先cmd检查服务端的共享目录 然后执行:showmo ...

  10. avue组件自定义按钮/标题/内容/搜索栏

    话不多说 笔记直接分享!! 一.自定义crud搜索栏组件 <template slot-scope="scope" slot="provinceCodeSearch ...