亚洲免费在线-亚洲免费在线播放-亚洲免费在线观看-亚洲免费在线观看视频-亚洲免费在线看-亚洲免费在线视频

json in java 介紹

系統(tǒng) 1978 0

http://json-lib.sourceforge.net/usage.html 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:

  1. boolean []?boolArray?= new boolean []{ true , false , true };
  2. JSONArray?jsonArray?=?JSONArray.fromObject(?boolArray?);
  3. System.out.println(?jsonArray?);
  4. //?prints?[true,false,true]

  1. List?list?= new ArrayList();
  2. list.add(? “first” );
  3. list.add(? “second” );
  4. JSONArray?jsonArray?=?JSONArray.fromObject(?list?);
  5. System.out.println(?jsonArray?);
  6. //?prints?["first","second"]

  1. JSONArray?jsonArray?=?JSONArray.fromObject( “['json','is','easy']“ );
  2. System.out.println(?jsonArray?);
  3. //?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:

  1. Map?map?= new HashMap();
  2. map.put(? “name” , “json” );
  3. map.put(? “bool” ,?Boolean.TRUE?);
  4. map.put(? “int” , new Integer( 1 )?);
  5. map.put(? “arr” , new String[]{ “a” , “b” }?);
  6. map.put(? “func” , “function(i){?return?this.arr[i];?}” );
  7. JSONObject?json?=?JSONObject.fromObject(?map?);
  8. System.out.println(?jsonObject?);
  9. //?prints?["name":"json","bool":true,"int":1,"arr":["a","b"],”func”:function(i){?return?this.arr[i];?}]

  1. class MyBean{
  2. private String?name?= “json” ;
  3. private int pojoId?= 1 ;
  4. private char []?options?= new char []{ ‘a(chǎn)’ , ‘f’ };
  5. private String?func1?= “function(i){?return?this.options[i];?}” ;
  6. private JSONFunction?func2?= new JSONFunction( new String[]{ “i” }, “return?this.options[i];” );
  7. //?getters?&?setters
  8. }
  9. JSONObject?jsonObject?=?JSONObject.fromObject(? new MyBean()?);
  10. System.out.println(?jsonObject?);
  11. /*?prints
  12. {”name”:”json”,”pojoId”:1,”options”:["a","f"],
  13. “func1″:function(i){?return?this.options[i];},
  14. “func2″:function(i){?return?this.options[i];}}
  15. */

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:

  1. String?json?= “{name=\”json\”,bool:true,int:1,double:2.2,func:function(a){?return?a;?},array:[1,2]}” ;
  2. JSONObject?jsonObject?=?JSONObject.fromObject(?json?);
  3. Object?bean?=?JSONObject.toBean(?jsonObject?);
  4. assertEquals(?jsonObject.get(? “name” ),?PropertyUtils.getProperty(?bean, “name” )?);
  5. assertEquals(?jsonObject.get(? “bool” ),?PropertyUtils.getProperty(?bean, “bool” )?);
  6. assertEquals(?jsonObject.get(? “int” ),?PropertyUtils.getProperty(?bean, “int” )?);
  7. assertEquals(?jsonObject.get(? “double” ),?PropertyUtils.getProperty(?bean, “double” )?);
  8. assertEquals(?jsonObject.get(? “func” ),?PropertyUtils.getProperty(?bean, “func” )?);
  9. List?expected?=?JSONArray.toList(?jsonObject.getJSONArray(? “array” )?);
  10. Assertions.assertListEquals(?expected,?(List)?PropertyUtils.getProperty(?bean,? “array” )?);

Convert to Bean:

  1. String?json?= “{bool:true,integer:1,string:\”json\”}” ;
  2. JSONObject?jsonObject?=?JSONObject.fromObject(?json?);
  3. BeanA?bean?=?(BeanA)?JSONObject.toBean(?jsonObject,?BeanA. class );
  4. assertEquals(?jsonObject.get(? “bool” ),?Boolean.valueOf(?bean.isBool()?)?);
  5. assertEquals(?jsonObject.get(? “integer” ), new Integer(?bean.getInteger()?)?);
  6. 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:

  1. class MyBean{
  2. private List?data;
  3. //?getters?&?setters
  4. }
  5. class Person{
  6. private String?name;
  7. //?getters?&?setters
  8. }
  9. String?json?=? “{’data’:[{'name':'Wallace'},{'name':'Grommit'}]}” ;
  10. Map?classMap?=? new HashMap();
  11. classMap.put(? “data” ,?Person. class );
  12. MyBean?bean?=?JSONObject.toBean(?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:

  1. Morpher?dynaMorpher?= new BeanMorpher(?Person. class ,?JSONUtils.getMorpherRegistry()?);
  2. morpherRegistry.registerMorpher(?dynaMorpher?);
  3. List?output?=? new ArrayList();
  4. for (?Iterator?i?=?bean.getData().iterator();?i.hasNext();?){
  5. output.add(?morpherRegistry.morph(?Person. class ,?i.next()?)?);
  6. }
  7. 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(chǎn)’ 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
  1. JSONObject?json?= new JSONObject( true );
  2. String?xml?=?XMLSerializer.write(?json?);

  1. < o class = “object” null = “true” >

  1. JSONObject?json?=?JSONObject.fromObject( “{\”name\”:\”json\”,\”bool\”:true,\”int\”:1}” );
  2. String?xml?=?XMLSerializer.write(?json?);

  1. < o class = “object” >
  2. < name type = “string” > json </ name >
  3. < bool type = “boolean” > true </ bool >
  4. < int type = “number” > 1 </ int >
  5. </ o >

  1. JSONArray?json?=?JSONArray.fromObject( “[1,2,3]“ );
  2. String?xml?=?XMLSerializer.write(?json?);

  1. < a class = “array” <
  2. < e type = “number” > 1 </ e >
  3. < e type = “number” > 2 </ e >
  4. < e type = “number” > 3 </ e >
  5. </ 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
  1. < a class = “array” >
  2. < e type = “function” params = “i,j” >
  3. return?matrix[i][j];
  4. </ e >
  5. </ a >

  1. JSONArray?json?=?(JSONArray)?XMLSerializer.read(?xml?);
  2. System.out.println(?json?);
  3. //?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.

? 2006-2007 Json-lib

json in java 介紹


更多文章、技術(shù)交流、商務合作、聯(lián)系博主

微信掃碼或搜索:z360901061

微信掃一掃加我為好友

QQ號聯(lián)系: 360901061

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。

【本文對您有幫助就好】

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長會非常 感謝您的哦!!!

發(fā)表我的評論
最新評論 總共0條評論
主站蜘蛛池模板: 欧美成人三级一区二区在线观看 | 欧美视频www| 2022国产91精品久久久久久 | 91探花视频在线观看 | 国产自产视频在线观看香蕉 | 国产精品自在自线免费观看 | 欧美日韩一区二区三区麻豆 | 国产精品视频网站 | 亚洲国产欧美精品 | 国产午夜精品久久久久免费视 | 天天拍拍天天爽免费视频 | 亚洲一区二区三区高清 不卡 | 久久精品国产一区二区小说 | 奇米影视7777777 | 蜜桃破解版免费看nba | 99热这里有精品 | 国产伦精品一区二区三区四区 | 亚洲一区二区三区精品视频 | 香蕉视频网站入口 | 国产成综合 | 亚洲精品欧洲一区二区三区 | 国产视频二区在线观看 | 男人天堂视频网 | 久热国产视频 | 亚洲综合一区二区 | 国产精品亚洲一区二区麻豆 | 福利视频一区二区 | 国产精品免费久久久久影院小说 | 免费观看欧美精品成人毛片能看的 | 国产欧美一区二区精品性色99 | 免费观看成人碰视频公开 | 最新国产精品久久精品 | 114一级毛片免费观看 | 欧美顶级毛片在线播放 | 蝌蚪久久| 亚洲国产综合自在线另类 | 色偷偷亚洲精品一区 | 国产精品公开免费视频 | 国产深夜福利19禁在线播放 | 91青青青 | 五月天丁香婷婷综合 |