`

json-lib入门学习

    博客分类:
  • j2se
 
阅读更多

json-lib入门学习

1 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.

2 Working with arrays and collections(JSONArray)

  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.

2.1 Examples:

2.1.1 Array

boolean[] boolArray = new boolean[]{true,false,true};  

JSONArray jsonArray = JSONArray.fromObject( boolArray );  

System.out.println( jsonArray );  

// prints [true,false,true]  

2.1.2 List

List list = new ArrayList();  

list.add( "first" );  

list.add( "second" );  

JSONArray jsonArray = JSONArray.fromObject( list );  

System.out.println( jsonArray );  

// prints ["first","second"]  

2.1.3 String

JSONArray jsonArray = JSONArray.fromObject( "['json','is','easy']" );  

System.out.println( jsonArray );  

// prints ["json","is","easy"]  

3 Working with objects(JSONObject)

3.1 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.

3.1.1 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]; }]  

3.1.2 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.

3.2 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.


3.2.1 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" ) );

3.2.2 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() );  

3.2.3 Caution

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 );  


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 );  

4 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.

4.1 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.

 

4.2 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

 

4.3 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入门学习文档

    入门学习JSon-lib2.4,首先需要了解以下几个关键概念: 1. **JSON对象**:在JSON中,对象是一个无序的键值对集合,用花括号{}包裹。每个键都是一个字符串,后面跟着一个冒号,冒号后面是对应的值,键值对之间用逗号...

    json-lib入门

    在本文中,我们将探讨`json-lib`的入门知识,包括其主要功能、使用方法以及如何通过提供的源码和工具进行学习和开发。 首先,`json-lib`的主要功能是将Java对象转换成JSON格式的字符串,同时也能将JSON字符串反序列...

    JSON-LIB快速入门(转)

    JSON-LIB快速入门指南 JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,它易于人阅读和编写,同时也易于机器解析和生成。...通过深入学习和实践这些示例代码,您可以熟练掌握JSON-LIB的基本用法。

    JSON-LIB快速入门

    在JSON-LIB的快速入门中,我们首先需要了解JSON的基本结构。JSON主要由两种基本类型构成:对象和数组。对象是以花括号{}包围的键值对集合,键是字符串,值可以是各种JSON数据类型,如字符串、数字、布尔值、null、...

    JSON从入门到精通,JSON与action的结合,json-lib等

    JSON从入门到精通,JSON与action的结合,json-lib等

    json-search-core-lib

    综上所述,"json-search-core-lib" 提供了一种基于Python的解决方案,帮助开发者更有效地在JSON数据中进行搜索操作,结合其源码、文档和测试资源,使用者可以深入学习JSON处理和Python编程的相关知识。

    json入门讲解的总结

    JSON,全称JavaScript Object Notation,是一种轻量级的数据交换格式。它的设计目标是易于人阅读和编写,同时也便于机器解析和生成。...学习并掌握JSON的使用,对于提升开发效率和优化应用性能至关重要。

    simple-jsonrpc-js:简单的jsonrpc javascript库。 生成并解析json rpc消息

    script src =" https://cdn.privex.io/lib/simple-jsonrpc/master/simple-jsonrpc-js.min.js " > </ script > < script > // Create a Simple-JsonRPC object which can call ...

    react-lib:React库入门模板

    用于通过npm分发的React组件库的入门模板。 技术领域 React Webpack 巴别塔 样式化的组件 笑话 酵素 如何使用此存储库作为模板 克隆此仓库的主分支: $ git clone --single-branch ...

    Struts2 json插件入门指南.pdf

    ### Struts2 JSON插件入门知识点详解 #### 1. 依赖包 - **Struts2 必需的 6 个 jar 包** - `commons-fileupload-1.2.2.jar`: 提供了文件上传功能的支持。 - `commons-io-2.0.1.jar`: 用于处理I/O操作,简化输入...

    微信jssdk开发java+jsp源码

    微信开发入门教程 jssdk,通过config接口注入权限验证配置java+jsp微信开发教程,功能:扫描...包含json相关依赖jar包,json-lib-2.3-jdk15.jar,ezmorph-1.0.6.jar,以及httpclient-4.5.3.jar,httpcore-4.4.6.jar等。

    googleads-php-lib:适用于PHP的Google Ads API客户端库(AdWords和Ad Manager)

    在该库的composer.json中可以找到系统要求和依赖性。 有关更多详细信息,请参。 该库取决于 。 如果您尚未在计算机上安装它,请遵循或。 在本指南的其余部分中,我们假设您使用的是Linux / Unix / OS X,并且已安装...

    (知识引用自)廖雪峰-JavaScript-Python-Git-教程-by-it-ebooks-_z-lib.org_1

    1. **Python简介**:Python易于学习,适合初学者入门。 2. **安装Python**:Python通过官方网站下载并安装,同时安装Python解释器。 3. **第一个Python程序**:简单的"Hello, World!"程序。 4. **数据类型和变量*...

    react-lib:React库的项目模板

    使用您的项目详细信息更新package.json 更新README.md和CHANGELOG.md 生成项目: yarn build生成或npm run build 验证输出束的尺寸与yarn size或npm run size yarn lint项目: yarn lint或npm run lint 运行单元...

    iso-lib-starter:使用汇总创建可重用的,现代的,同构的javascript库的入门者

    iso-lib-starter 使用汇总创建可重用的,现代的,同构的javascript库的入门程序。 要求 用法 生成新的存储库 打开终端, clone并cd到新的存储库中 在终端中时,复制,粘贴并在以下脚本中运行以设置公用文件 ( # ...

    typescript-lib-starter:用于现代TypeScript库的Stater套件。 生成准备在npm上发布的JS

    TypeScript库启动器 适用于现代TypeScript库的入门工具包。 生成准备在npm上发布JavaScript。 包括电池。 时期。 和用于格式化和整理用于测试执行进行测试和代码覆盖用于测试报告工作流程的配置文件克隆仓库$ git ...

Global site tag (gtag.js) - Google Analytics