`
inspire_xg
  • 浏览: 27873 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

How to use json-lib

    博客分类:
  • Json
 
阅读更多
How to use json-lib
Using the JSONSerializer
Working with arrays and collections
Working with objects
Working with XML

Using the JSONSerializer
JSONSerializer can transform any java object to JSON notation and back with a simple and clean interface, leveraging all the builders in JSONObject and JSONArray. To transform a java obect into JSON use JSONSerializer.toJSON(). To transform a valid JSON value (by JSON, I mean an Object implementing that interface), use toJava(). The last method is an instance method because the serializer needs special configuration to transform a JSON value to a bean class, array, List or DynaBean.

Working with arrays and collections
The simplest way to create a JSONArray from a java array or collection is through the static factory methods from JSONArray. JSONArray.fromObject() will inspect its parameter and call the correct factory or constructor.

Examples:

boolean[] boolArray = new boolean[]{true,false,true};  
JSONArray jsonArray = JSONArray.fromObject( boolArray );  
System.out.println( jsonArray );  
// prints [true,false,true] 
   boolean[] boolArray = new boolean[]{true,false,true};
   JSONArray jsonArray = JSONArray.fromObject( boolArray );
   System.out.println( jsonArray );
   // prints [true,false,true]List list = new ArrayList();  
list.add( "first" );  
list.add( "second" );  
JSONArray jsonArray = JSONArray.fromObject( list );  
System.out.println( jsonArray );  
// prints ["first","second"] 
   List list = new ArrayList();
   list.add( "first" );
   list.add( "second" );
   JSONArray jsonArray = JSONArray.fromObject( list );
   System.out.println( jsonArray );
   // prints ["first","second"]JSONArray jsonArray = JSONArray.fromObject( "['json','is','easy']" );  
System.out.println( jsonArray );  
// prints ["json","is","easy"] 
   JSONArray jsonArray = JSONArray.fromObject( "['json','is','easy']" );
   System.out.println( jsonArray );
   // prints ["json","is","easy"]
Working with objects
From Beans & Maps to JSON
The simplest way to create a JSONObject from a bean or Map is through the static factory methods from JSONObject. JSONObject.fromObject() will inspect its parameter and call the correct factory or constructor.

Examples:

Map map = new HashMap();  
map.put( "name", "json" );  
map.put( "bool", Boolean.TRUE );  
map.put( "int", new Integer(1) );  
map.put( "arr", new String[]{"a","b"} );  
map.put( "func", "function(i){ return this.arr[i]; }" );  
 
JSONObject jsonObject = JSONObject.fromObject( map );  
System.out.println( jsonObject );  
// prints ["name":"json","bool":true,"int":1,"arr":["a","b"],"func":function(i){ return this.arr[i]; }] 
   Map map = new HashMap();
   map.put( "name", "json" );
   map.put( "bool", Boolean.TRUE );
   map.put( "int", new Integer(1) );
   map.put( "arr", new String[]{"a","b"} );
   map.put( "func", "function(i){ return this.arr[i]; }" );

   JSONObject jsonObject = JSONObject.fromObject( map );
   System.out.println( jsonObject );
   // prints ["name":"json","bool":true,"int":1,"arr":["a","b"],"func":function(i){ return this.arr[i]; }]class MyBean{  
   private String name = "json";  
   private int pojoId = 1;  
   private char[] options = new char[]{'a','f'};  
   private String func1 = "function(i){ return this.options[i]; }";  
   private JSONFunction func2 = new JSONFunction(new String[]{"i"},"return this.options[i];");  
 
   // getters & setters  
   ...  
}  
 
JSONObject jsonObject = JSONObject.fromObject( new MyBean() );  
System.out.println( jsonObject );  
/* prints 
  {"name":"json","pojoId":1,"options":["a","f"], 
  "func1":function(i){ return this.options[i];}, 
  "func2":function(i){ return this.options[i];}} 
*/ 
   class MyBean{
      private String name = "json";
      private int pojoId = 1;
      private char[] options = new char[]{'a','f'};
      private String func1 = "function(i){ return this.options[i]; }";
      private JSONFunction func2 = new JSONFunction(new String[]{"i"},"return this.options[i];");

      // getters & setters
      ...
   }

   JSONObject jsonObject = JSONObject.fromObject( new MyBean() );
   System.out.println( jsonObject );
   /* prints
     {"name":"json","pojoId":1,"options":["a","f"],
     "func1":function(i){ return this.options[i];},
     "func2":function(i){ return this.options[i];}}
   */

CAUTION: when parsing, JSONObject and JSONArray will check for cycles in the hierarchy, throwing an exception if one is found. You can change this behavior by registering a CycleDetectionStrategy. 


From JSON to Beans
Json-lib can transform JSONObjects to either a DynaBean or an specific bean class.
When using DynaBean all arrays are converted to Lists, when using an specific bean class the transformation will use type conversion if necessary on array properties.

Convert to DynaBean:

String json = "{name=\"json\",bool:true,int:1,double:2.2,func:function(a){ return a; },array:[1,2]}";  
JSONObject jsonObject = JSONObject.fromObject( json );  
Object bean = JSONObject.toBean( jsonObject );  
assertEquals( jsonObject.get( "name" ), PropertyUtils.getProperty( bean, "name" ) );  
assertEquals( jsonObject.get( "bool" ), PropertyUtils.getProperty( bean, "bool" ) );  
assertEquals( jsonObject.get( "int" ), PropertyUtils.getProperty( bean, "int" ) );  
assertEquals( jsonObject.get( "double" ), PropertyUtils.getProperty( bean, "double" ) );  
assertEquals( jsonObject.get( "func" ), PropertyUtils.getProperty( bean, "func" ) );  
List expected = JSONArray.toList( jsonObject.getJSONArray( "array" ) );  
Assertions.assertListEquals( expected, (List) PropertyUtils.getProperty( bean, "array" ) ); 
   String json = "{name=\"json\",bool:true,int:1,double:2.2,func:function(a){ return a; },array:[1,2]}";
   JSONObject jsonObject = JSONObject.fromObject( json );
   Object bean = JSONObject.toBean( jsonObject );
   assertEquals( jsonObject.get( "name" ), PropertyUtils.getProperty( bean, "name" ) );
   assertEquals( jsonObject.get( "bool" ), PropertyUtils.getProperty( bean, "bool" ) );
   assertEquals( jsonObject.get( "int" ), PropertyUtils.getProperty( bean, "int" ) );
   assertEquals( jsonObject.get( "double" ), PropertyUtils.getProperty( bean, "double" ) );
   assertEquals( jsonObject.get( "func" ), PropertyUtils.getProperty( bean, "func" ) );
   List expected = JSONArray.toList( jsonObject.getJSONArray( "array" ) );
   Assertions.assertListEquals( expected, (List) PropertyUtils.getProperty( bean, "array" ) );
Convert to Bean:

String json = "{bool:true,integer:1,string:\"json\"}";  
JSONObject jsonObject = JSONObject.fromObject( json );  
BeanA bean = (BeanA) JSONObject.toBean( jsonObject, BeanA.class );  
assertEquals( jsonObject.get( "bool" ), Boolean.valueOf( bean.isBool() ) );  
assertEquals( jsonObject.get( "integer" ), new Integer( bean.getInteger() ) );  
assertEquals( jsonObject.get( "string" ), bean.getString() ); 
   String json = "{bool:true,integer:1,string:\"json\"}";
   JSONObject jsonObject = JSONObject.fromObject( json );
   BeanA bean = (BeanA) JSONObject.toBean( jsonObject, BeanA.class );
   assertEquals( jsonObject.get( "bool" ), Boolean.valueOf( bean.isBool() ) );
   assertEquals( jsonObject.get( "integer" ), new Integer( bean.getInteger() ) );
   assertEquals( jsonObject.get( "string" ), bean.getString() );
There are two special cases when converting to an specific bean, if the target bean has a Map property and it must contain other beans, JSONObject.toBean() will transform the nested beans into DynaBeans. If you need those nested beans transformed into an specific class, you can either postprocess the Map attribute or provide hints on JSONObject's attributes for conversion. JSONObject.toBean() may be passed a third argument, a Map, that will provide thos hints. Every key must be either the name of a property or a regular expression matching the object's properties, and the value must be a Class.

The second case is similar and it happens when the target bean has a Collection (List) as a property and it must contain other beans. In this case there is no way to provide hints for class conversion. The only possible solution is to postprocess the collection transforming each DynaBean into an specific bean.

To ease the postprocessing scenarios, EZMorph provides a Morpher capable of transforming a DynaBean into an specific bean, BeanMorpher
Example:

class MyBean{  
   private List data;  
   // getters & setters  
}  
 
class Person{  
   private String name;  
   // getters & setters  
}  
 
...  
 
String json = "{'data':[{'name':'Wallace'},{'name':'Grommit'}]}";  
Map classMap = new HashMap();  
classMap.put( "data", Person.class );  
MyBean bean = JSONObject.toBean( JSONObject.fromObject(json), MyBean.class, classMap ); 
   class MyBean{
      private List data;
      // getters & setters
   }

   class Person{
      private String name;
      // getters & setters
   }

   ...

   String json = "{'data':[{'name':'Wallace'},{'name':'Grommit'}]}";
   Map classMap = new HashMap();
   classMap.put( "data", Person.class );
   MyBean bean = JSONObject.toBean( JSONObject.fromObject(json), MyBean.class, classMap );
This yields a MyBean instance that has DynaBeans inside the 'data' attribute', so now comes the part of postprocessing, this can be done with an Iterator
Example:

Morpher dynaMorpher = new BeanMorpher( Person.class, JSONUtils.getMorpherRegistry() );  
morpherRegistry.registerMorpher( dynaMorpher );  
List output = new ArrayList();  
for( Iterator i = bean.getData().iterator(); i.hasNext(); ){  
   output.add( morpherRegistry.morph( Person.class, i.next() ) );  
}  
bean.setData( output ); 
   Morpher dynaMorpher = new BeanMorpher( Person.class, JSONUtils.getMorpherRegistry() );
   morpherRegistry.registerMorpher( dynaMorpher );
   List output = new ArrayList();
   for( Iterator i = bean.getData().iterator(); i.hasNext(); ){
      output.add( morpherRegistry.morph( Person.class, i.next() ) );
   }
   bean.setData( output );
To learn more about Morphers, please visit EZMorph's project site.

Working with XML
Working with XML has become easier since version 1.1. Transforming JSONObjects and JSONArrays from and to XML is done through the XMLSerializer.

From JSON to XML
Writing to JSON to XML is as simple as calling XMLSerializer.write(), but there are a lot of options that you may configure to get better control of the XML output. For example you may change the default names for the root element ('o' if object, 'a' if array), the default name for object (an object inside an array is "anonymous"), the default name for array (for the same reason as object), the default name for element (array items have no name). If you'd like to output namescape information but your JSON does not includes it, no problem, you have 8 methods that will let you register and manage namespaces; namespaces defined this way have precedence on any namespace declaration that may be inside the JSON. By default XMLSerializer will append special attributes to each xml element for easing the transformation back to JSON but you may configure it to skip appending those attributes. Any property on a JSONObject that begins with '@' will be treated as an attribute, any property named '#text' will be treated as a Text node.

Please review the javadoc for XMLSerializer to know more about the configurable options.

Code XML output
JSONObject json = new JSONObject( true );  
String xml = XMLSerializer.write( json ); 
   JSONObject json = new JSONObject( true );
   String xml = XMLSerializer.write( json ); <o class="object" null="true"> 
     
   <o class="object" null="true">
       
JSONObject json = JSONObject.fromObject("{\"name\":\"json\",\"bool\":true,\"int\":1}");  
String xml = XMLSerializer.write( json ); 
   JSONObject json = JSONObject.fromObject("{\"name\":\"json\",\"bool\":true,\"int\":1}");
   String xml = XMLSerializer.write( json ); <o class="object"> 
   <name type="string">json</name> 
   <bool type="boolean">true</bool> 
   <int type="number">1</int> 
</o> 
   <o class="object">
      <name type="string">json</name>
      <bool type="boolean">true</bool>
      <int type="number">1</int>
   </o>
   
JSONArray json = JSONArray.fromObject("[1,2,3]");  
String xml = XMLSerializer.write( json ); 
   JSONArray json = JSONArray.fromObject("[1,2,3]");
   String xml = XMLSerializer.write( json ); <a class="array"< 
   <e type="number">1</e> 
   <e type="number">2</e> 
   <e type="number">3</e> 
</a> 
   <a class="array"<
      <e type="number">1</e>
      <e type="number">2</e>
      <e type="number">3</e>
   </a>
   

From XML to JSON
XMLSerializer treats each element as a string unless a type parameter is specified.
JSONFunction needs an additional parameter that specifies that function's params.
All xml attributes will have the prefix '@' and text nodes will have the property name '#text'. XMLSerializer supports the rules outlined at Converting Between XML and JSON

XML input Code
<a class="array"> 
  <e type="function" params="i,j"> 
      return matrix[i][j];  
  </e> 
</a> 
   <a class="array">
     <e type="function" params="i,j">
         return matrix[i][j];
     </e>
   </a>
    JSONArray json = (JSONArray) XMLSerializer.read( xml );  
System.out.println( json );  
// prints [function(i,j){ return matrix[i][j]; }]  
   JSONArray json = (JSONArray) XMLSerializer.read( xml );
   System.out.println( json );
   // prints [function(i,j){ return matrix[i][j]; }]
   


CAUTION: when parsing, JSONObject and JSONArray will check for cycles in the hierarchy, throwing an exception if one is found. You can change this behavior by registering a CycleDetectionStrategy.
分享到:
评论
发表评论

文章已被作者锁定,不允许评论。

相关推荐

    json-lib 使用说明(How to use json-lib)【官网教程】

    json-lib 提供了强大的JSON支持,利用Ajax提交上来的JSON字符串进行解析,可以转化为POJO对象,可以从POJO转化为js可以识别的JSON对象。方便易用!

    Android代码-NetworkUtil-lib

    NetworkUtil-lib NetworkUilt is a fast and efficient open source network fetcher java class for Android which is use to make ...How to add this to your project? STEP 1. Add the JitPack repository t

    ICS delphixe10源码版

    Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The...

    spring-boot-reference.pdf

    6. Moving to Production 7. Advanced Topics II. Getting Started 8. Introducing Spring Boot 9. System Requirements 9.1. Servlet Containers 10. Installing Spring Boot 10.1. Installation Instructions for ...

    基于A*算法的往返式全覆盖路径规划改进及其Matlab实现

    内容概要:本文详细介绍了如何利用A*算法改进传统的往返式路径规划,解决扫地机器人在复杂环境中容易卡住的问题。首先构建了一个可视化的栅格地图用于模拟环境,然后引入了优先级运动规则,使机器人能够有规律地进行往返清扫。当遇到死角时,通过A*算法计算最佳逃生路径,确保机器人能够顺利脱困并继续完成清扫任务。实验结果显示,改进后的算法显著提高了清洁覆盖率,降低了路径重复率。此外,还讨论了一些潜在的优化方向,如动态调整启发函数权重、断点续传以及能耗模型等。 适合人群:对路径规划算法感兴趣的科研人员、自动化专业学生、扫地机器人开发者。 使用场景及目标:适用于需要高覆盖率和低重复率的室内清洁任务,旨在提高扫地机器人的工作效率和智能化水平。 其他说明:文中提供了详细的Matlab代码实现,并附带了仿真测试结果,有助于读者理解和复现该算法。

    爬取喜马拉雅听书(1).py

    爬取喜马拉雅听书(1)

    安卓向上传递数据学习笔记总结

    安卓向上传递数据学习笔记总结

    tigervnc-selinux-1.11.0-9.el8.x64-86.rpm.tar.gz

    1、文件说明: Centos8操作系统tigervnc-selinux-1.11.0-9.el8.rpm以及相关依赖,全打包为一个tar.gz压缩包 2、安装指令: #Step1、解压 tar -zxvf tigervnc-selinux-1.11.0-9.el8.tar.gz #Step2、进入解压后的目录,执行安装 sudo rpm -ivh *.rpm

    户外储能电源双向逆变器板生产资料及技术规格详解

    内容概要:本文详细介绍了户外储能电源双向逆变器板的技术资料及其特点。涵盖原理文件、PCB文件、源代码、电感与变压器规格参数等,适用于2KW(最大3KW)的户外储能电源。文中强调了双向软开关DC-DC设计、两颗M0+ 32位MCU的分工、SPWM调制方式、H桥IGBT的应用、详细的电气参数和技术特性。此外,还包括了SPWM信号生成代码示例、硬件设计细节、生产注意事项等。 适合人群:从事户外储能电源开发的技术人员、电子工程师、产品经理等。 使用场景及目标:帮助开发者快速掌握双向逆变器板的设计和生产要点,缩短产品研发周期,提高产品质量和可靠性。具体应用场景包括但不限于户外应急电源、便携式储能设备等。 其他说明:本文提供了丰富的技术细节和实践经验,如双向软开关DC-DC设计、SPWM调制、IGBT驱动、EMC整改记录等,有助于解决实际开发中的难题。同时,附带的实际案例展示了该方案的成功应用,进一步证明了其可行性和优越性。

    电能质量分析:间谐波分析.zip

    电子仿真教程,从基础到精通,每个压缩包15篇教程,每篇教程5000字以上。

    【计算机科学领域】美国计算机学会(ACM):组织架构、使命愿景、核心价值及活动项目介绍

    内容概要:美国计算机学会(ACM)是一个成立于1947年的国际性计算机专业组织,致力于推动计算机科学的发展,提供教育、资源和专业发展机会。ACM的使命是促进计算机科学和信息技术领域的进步,愿景是成为全球计算机专业人士的首选组织。其核心价值包括卓越、诚信、包容性、合作和创新。ACM定期举办学术会议,如SIGGRAPH和图灵奖颁奖典礼,出版高质量的学术期刊和会议论文集,涵盖人工智能、软件工程、网络安全等领域。此外,ACM还提供在线课程、研讨会、认证项目等教育资源,以及职业规划、网络机会和领导力培训等职业发展服务。ACM图灵奖被誉为“计算机界的诺贝尔奖”,每年颁发给对计算机科学和技术做出重大贡献的个人。; 适合人群:计算机科学领域的专业人士、教育工作者、工程师和学生。; 使用场景及目标:①了解计算机科学领域的最新研究成果和发展趋势;②获取高质量的教育资源和职业发展机会;③参与计算机科学领域的学术交流和合作。; 其他说明:ACM作为一个全球性的组织,在教育、研究和行业实践中发挥着重要作用,推动了技术创新和社会进步。

    最新版logstash-8.17.4-windows-x86-64.zip

    logstash-8.17.4-windows-x86_64.zip

    一个基于Springboot使用Aspect实现一个切面,以记录日志为例

    springboot 一个基于Springboot使用Aspect实现一个切面,以记录日志为例

    音箱底部折边设备sw22可编辑_三维3D设计图纸_包括零件图_机械3D图可修改打包下载_三维3D设计图纸_包括零件图_机械3D图可修改打包下载.zip

    音箱底部折边设备sw22可编辑_三维3D设计图纸_包括零件图_机械3D图可修改打包下载_三维3D设计图纸_包括零件图_机械3D图可修改打包下载.zip

    基于Python Django MySQL的个性化图书推荐系统:协同过滤算法及远程部署实现

    内容概要:本文详细介绍了如何使用Python、Django和MySQL构建一个完整的个性化图书推荐系统。系统从前端界面设计、后端逻辑实现到数据库设计,涵盖了用户管理、图书管理、评分系统等功能模块。重点讲解了基于用户和项目的协同过滤算法实现,以及在用户评分数据不足时的标签推荐备份方案。此外,还包括了系统部署、测试和优化的具体步骤,如云服务器部署、性能测试、数据库优化等。 适合人群:具备一定Python和Web开发基础的研发人员,尤其是对推荐系统感兴趣的技术爱好者。 使用场景及目标:适用于希望深入了解图书推荐系统的工作原理和实现细节的技术人员。目标是帮助读者掌握从零开始搭建一个完整的个性化推荐系统的方法,包括前后端开发、算法实现和系统部署。 其他说明:文中提供了大量代码示例和实战经验,如数据库设计、爬虫实现、权限管理等,有助于读者更好地理解和应用相关技术。

    Ai和python学习资料

    Ai和python学习资料

    文本摘要.py

    文本摘要

    冲击试验机sw22_三维3D设计图纸_包括零件图_机械3D图可修改打包下载_三维3D设计图纸_包括零件图_机械3D图可修改打包下载.zip

    冲击试验机sw22_三维3D设计图纸_包括零件图_机械3D图可修改打包下载_三维3D设计图纸_包括零件图_机械3D图可修改打包下载.zip

    Java开发MybatisPlus框架详解:增强Mybatis功能实现高效CRUD操作与代码生成

    内容概要:本文详细介绍了MyBatis Plus(MP),它是MyBatis的增强工具,旨在简化CRUD操作、提高开发效率。其主要功能包括内置分页插件、简化CRUD操作以及代码生成器。使用时只需引入相应依赖,自定义Mapper接口继承BaseMapper泛型接口,并通过实体类反射获取数据库表信息。文章还介绍了常用注解如@TableName、@TableId、@TableField、@TableLogic和@Version,配置项如全局配置、类型别名和Mapper文件路径,以及核心功能如批量插入、分页查询、条件构造器(Wrapper)等。此外,扩展功能涵盖逻辑删除、枚举处理器和JSON处理器,插件功能则包括分页插件的配置和使用。 适合人群:具备一定Java开发经验,尤其是熟悉MyBatis框架的开发者,特别是那些希望提高开发效率、减少重复代码的工作1-3年研发人员。 使用场景及目标:①简化数据库操作,提高开发效率;②快速生成代码,减少手动编写SQL语句的工作量;③实现分页查询、逻辑删除、枚举和JSON字段处理等高级功能,提升应用的灵活性和可维护性。 其他说明:本文不仅提供了MyBatis Plus的功能介绍和使用方法,还深入探讨了条件构造器(Wrapper)的使用技巧,帮助开发者更好地理解和掌握这一强大的工具。在实际开发中,合理利用这些功能可以显著提高开发效率和代码质量。建议在学习过程中结合具体项目实践,逐步掌握各个功能的应用场景和最佳实践。

    电路仿真:射频电路仿真.zip

    电子仿真教程,从基础到精通,每个压缩包15篇教程,每篇教程5000字以上。

Global site tag (gtag.js) - Google Analytics