Java constructs and parses JSON data in one of two ways

Source: Internet
Author: User

A lot of JSON constructs and parsing tools are published on www.json.org, in which Org.json and json-lib are relatively simple, but there are some differences in the use of the two. The following first describes an example of how to construct and parse JSON data using Json-lib.

how to construct and parse JSON data with Org.son see my next blog post: Two ways to construct and parse JSON data two

First, Introduction

The Json-lib package is a Beans,collections,maps,java arrays and XML and JSON to convert the package, is mainly used to parse JSON data, on its official website http://www.json.org/detailed explanation, Interested to be able to study.

Download jar Dependency Package: You can go here to download

Iii. Introduction to the basic methods

1. Convert list collection to JSON method

11. Convert list collection to JSON method2 3  4 5List List =NewArrayList ();6List.add ("First" );7List.add ("Second" );8Jsonarray JsonArray2 =jsonarray.fromobject (list);9  Ten  One2. Map collection into JSON method A  -Map map =NewHashMap (); theMap.put ("name", "JSON"); -Map.put ("bool", boolean.true); -Map.put ("int",NewInteger (1)); -Map.put ("Arr",NewString[] {"A", "B" }); +Map.put ("func", "function (i) {return this.arr[i];}"); -Jsonobject JSON =jsonobject.fromobject (map); + Copy Code A3. The bean is converted into JSON code at -Jsonobject Jsonobject = Jsonobject.fromobject (NewJsonbean ()); -4. Array into JSON code -  - Boolean[] Boolarray =New Boolean[] {true,false,true }; -Jsonarray jsonArray1 =Jsonarray.fromobject (boolarray); in5. Convert general data to JSON code -  toJsonarray jsonArray3 = Jsonarray.fromobject ("[' json ', ' is ', ' easy ']" ); +6. Beans convert to JSON code -  *List List =NewArrayList (); $JsonBean2 JB1 =NewJsonBean2 ();Panax NotoginsengJb1.setcol (1); -Jb1.setrow (1); theJb1.setvalue ("XX"); +  AJsonBean2 JB2 =NewJsonBean2 (); theJb2.setcol (2); +Jb2.setrow (2); -Jb2.setvalue (""); $  $ List.add (JB1); - List.add (JB2); -Jsonarray ja =jsonarray.fromobject (list);

Iv. Demonstration Examples

Here are some basic common methods for testing

1  PackageCom.json;2 3 Importjava.util.ArrayList;4 ImportJava.util.HashMap;5 Importjava.util.List;6 ImportJava.util.Map;7 8 ImportNet.sf.json.JSONArray;9 ImportNet.sf.json.JSONObject;Ten  One /** A * Construct and parse JSON data using Json-lib -  *  -  * @authorAlexia the * @date 2013/5/23 -  * -  */ -  Public classJsontest { +  -     /** + * Construct JSON data A      *  at      * @return -      */ -      Public StaticString Buildjson () { -  -         //JSON-formatted data parsing objects -Jsonobject Jo =NewJsonobject (); in  -         //The following constructs two maps, a list, and an employee object tomap<string, string> map1 =NewHashmap<string, string>(); +Map1.put ("name", "Alexia"); -Map1.put ("Sex", "female"); theMap1.put ("Age", "23"); *  $map<string, string> map2 =NewHashmap<string, string>();Panax NotoginsengMap2.put ("name", "Edward"); -Map2.put ("Sex", "male"); theMap2.put ("Age", "24"); +  Alist<map> list =NewArraylist<map>(); the List.add (MAP1); + List.add (MAP2); -  $Employee Employee =NewEmployee (); $Employee.setname ("Wjl"); -Employee.setsex ("female"); -Employee.setage (24); the  -         //convert map to Jsonarray dataWuyiJsonarray JA1 =Jsonarray.fromobject (MAP1); the         //Convert list to Jsonarray data -Jsonarray JA2 =jsonarray.fromobject (list); Wu         //converting beans to Jsonarray data -Jsonarray JA3 =Jsonarray.fromobject (employee); About  $System.out.println ("Jsonarray Object Data format:"); - System.out.println (ja1.tostring ()); - System.out.println (ja2.tostring ()); - System.out.println (ja3.tostring ()); A  +         //constructs JSON data, including a map and an employee object theJo.put ("Map", JA1); -Jo.put ("Employee", JA2); $System.out.println ("\ n final constructed JSON data format:"); the System.out.println (jo.tostring ()); the  the         returnjo.tostring (); the  -     } in  the     /** the * Parse JSON data About      *  the      * @paramjsonstring JSON data string the      */ the      Public Static voidParsejson (String jsonstring) { +  -         //take employee as an example to analyze, map similar theJsonobject JB =Jsonobject.fromobject (jsonstring);BayiJsonarray ja = Jb.getjsonarray ("Employee"); the  theList<employee> emplist =NewArraylist<employee>(); -  -         //Loop to add an employee object (there may be multiple) the          for(inti = 0; I < ja.size (); i++) { theEmployee Employee =NewEmployee (); the  theEmployee.setname (Ja.getjsonobject (i). getString ("name")); -Employee.setsex (Ja.getjsonobject (i). getString ("Sex")); theEmployee.setage (Ja.getjsonobject (i). GetInt ("Age")); the  the Emplist.add (employee);94         } the  theSystem.out.println ("\ n convert JSON data to employee object:"); the          for(inti = 0; I < emplist.size (); i++) {98Employee emp =Emplist.get (i); AboutSystem.out.println ("Name:" + emp.getname () + "Sex:" -+ emp.getsex () + "Age:" +emp.getage ());101         }102 103     }104  the     /**106      * @paramargs107      */108      Public Static voidMain (string[] args) {109         //TODO auto-generated Method Stub the 111 Parsejson (Buildjson ()); the     }113  the}

The operation results are as follows

V. Comparison with Org.json

The use of Json-lib and Org.json is almost the same, and I have summed up the difference with two points:

1. Org.json is much lighter than Json-lib, the former does not depend on any other jar packages, while the latter relies on ezmorph and Commons's lang, logging, Beanutils, collections, and other components

2. Json-lib in the construction of beans and parsing beans more convenient than Org.json, Json-lib can be directly with the bean conversion, and Org.json can not directly with the bean conversion and need map as a transit, if the bean to JSON data, first need to convert the bean to M The AP then turns the map into JSON, which is more cumbersome.

In short, or that sentence-suitable for their own is the best, we need to choose which method to use to resolve. Finally, we introduce two tools for parsing JSON data: One is online tool Jsonedit (http://braincast.nl/samples/jsoneditor/) and the other is Eclipse's plugin json Tree Analyzer, are very useful, recommended for everyone to use!

Java constructs and parses JSON data in one of two ways

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.