Java JSON组成和解析

news/2024/10/2 16:28:35

  本框架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;}}@Overridepublic char charAt(int index) {return this.cache[index];}@Overridepublic int length() {return this.count;}@Overridepublic 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;}@Overridepublic 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 

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.ryyt.cn/news/44776.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈,一经查实,立即删除!

相关文章

Flink - [06] 状态管理

题记部分 一、Flink中的状态由一个任务维护,并且用来计算某个结果的所有数据,都属于这个任务的状态。 可以认为状态就是一个本地变量,可以被任务的业务逻辑访问。 Flink会进行状态管理,包括状态一致性、故障处理以及高效存储和访问,以便开发人员可以专注于应用程序的逻辑…

tableau图表样式/格式

1、色阶2、饼图变形

Linux 提权-Capabilities

本文通过 Google 翻译 Capabilities – Linux Privilege Escalation - Juggernaut-Sec 这篇文章所产生,本人仅是对机器翻译中部分表达别扭的字词进行了校正及个别注释补充。导航0 前言 1 什么是 Capabilities ? 2 枚举 Capabilities2.1 枚举 Capabilities - 手动方法2.1.1 进…

C# 设置PDF表单不可编辑、或提取PDF表单数据

PDF表单是PDF中的可编辑区域,允许用户填写指定信息。当表单填写完成后,有时候我们可能需要将其设置为不可编辑,以保护表单内容的完整性和可靠性。或者需要从PDF表单中提取数据以便后续处理或分析。 之前文章详细介绍过如何使用免费Spire.PDF库通过C# 创建、填写表单,本文将…

Python工具箱系列(五十三)

​​水印 水印是一种常见的图片处理需求。当既需要展示,又需要保护知识产权时,就需要使用文字或者图片来打水印。下面的代码展示了文字水印与图片水印的过程。 ​--javascripttypescriptbashsqljsonhtmlcssccppjavarubypythongorustmarkdown from pathlib import Pathfrom PI…

高效开发系列:鸿蒙原生app套用混合app开发思路

使用混合App开发思路来开发鸿蒙原生App是一种可行的方案。该方案可以提高开发效率、降低开发成本,但同时也存在一些劣势。开发者可以根据自己的具体需求来决定是否采用这种方案。随着鸿蒙OS生态的不断完善,鸿蒙原生App开发也将迎来新的机遇和挑战。相信在不久的将来,鸿蒙原生…

操作系统B期末复习(STD)

操作系统1、什么是操作系统 基本特征是什么? 操作系统是配置在计算机硬件上的第一层软件,是对硬件系统的首次扩充2、PCB TCB FCB 相关内容 PCB: ①基本信息:进程控制块,又叫进程表,是操作系统中最重要的记录型数据结构。记录了操作系统所需的,用于描述进程的当前情况以及…

React中AntDesign upload组件 自定义请求将多个上传请求合并成一个并

接口文档核心代码 const ImportPictureUpload = () => {const [fileList, setFileList] = useState([])const onBeforeUpload = (file: any, fileList: any) => {setFileList(fileList)return false;}useEffect(() => {if(fileList.length > 0) {onCustomRequest()…