Java parsing JSON

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.

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.

Second, download the jar package, you can go here to download http://down.51cto.com/data/2094833

650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M01/73/52/wKioL1X6X9fD0L2SAACkDtTuOuo796.jpg "title=" 11111. PNG "alt=" wkiol1x6x9fd0l2saackdttuouo796.jpg "/>

Three, the introduction of JSON

1. Convert list collection to JSON method

List List = new ArrayList (), List.add ("first"), List.add ("second"); Jsonarray jsonArray2 = jsonarray.fromobject (list);

2 . Map collection into JSON method

650) this.width=650; "src=" Http://common.cnblogs.com/images/copycode.gif "alt=" Copy Code "style=" margin:0px;padding:0px ; border:none; "/>

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 JSON = jsonobject.fromobject (map);

650) this.width=650; "src=" Http://common.cnblogs.com/images/copycode.gif "alt=" Copy Code "style=" margin:0px;padding:0px ; border:none; "/>

3 . The bean is converted into JSON code

Jsonobject jsonobject = jsonobject.fromobject (New Jsonbean ());

4 . Array into JSON code

boolean[] Boolarray = new boolean[] {true, false, true}; Jsonarray jsonArray1 = Jsonarray.fromobject (Boolarray);

5 . Convert general data to JSON code

Jsonarray jsonArray3 = Jsonarray.fromobject ("[' json ', ' is ', ' easy ']");

6 . Beans Convert to JSON code

650) this.width=650; "src=" Http://common.cnblogs.com/images/copycode.gif "alt=" Copy Code "style=" margin:0px;padding:0px ; border:none; "/>

List List = new ArrayList (); JsonBean2 jb1 = new JsonBean2 () Jb1.setcol (1); Jb1.setrow (1); Jb1.setvalue ("xx"); JsonBean2 jb2 = new JsonBean2 () Jb2.setcol (2); Jb2.setrow (2); Jb2.setvalue (""); List.add (JB1); List.add (JB2); Jsonarray ja = jsonarray.fromobject (list);

650) this.width=650; "src=" Http://common.cnblogs.com/images/copycode.gif "alt=" Copy Code "style=" margin:0px;padding:0px ; border:none; "/>

Iv. code Examples

import java.util.arraylist;import java.util.hashmap;import java.util.list;import  java.util.map;import net.sf.json.jsonarray;import net.sf.json.jsonobject;public class  jsontest {/** *  @param  args */public static void main (String[]  args)  {jsontest.buildjson ();} /**     *  Structuring JSON data      *       *  @return      */    public static string  buildjson ()  {        // json Format Data resolution object          jsonobject jo = new jsonobject ();         //  below constructs two maps, a list, and an employee object          Map<string, string> map1 = new hashmap<string, string> ();          map1.put ("Name",  "Alexia");         map1.put ("Sex",  "female");         map1.put ("Age",   "        map<string, string> map2 =");  new HashMap<String, String> ();         map2.put (" Name ", " Edward ")         map2.put (" Sex ", " male ");         map2.put ("Age",  ";      ")   List<Map> list = new ArrayList<Map> ();         list.add (MAP1);         list.add (MAP2);         employee employee = new employee ();         empLoyee.setname ("Wjl");         employee.setsex ("female");         employee.setage (        //);   Convert map to Jsonarray data         JSONArray ja1 =  Jsonarray.fromobject (MAP1);        //  convert list to JSONArray data          jsonarray ja2 = jsonarray.fromobject (list);         //  converting beans to Jsonarray data          jsonarray ja3 = jsonarray.fromobject (employee);         system.out.println ("Jsonarray Object Data Format:");         System.out.println (Ja1.tostring ());         system.out.println ( Ja2.tostring ()); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBsp; system.out.println (Ja3.tostring ());        //  constructs JSON data, Includes a map and an employee object         jo.put ("map", &NBSP;JA1);         jo.put ("Employee", &NBSP;JA2);         System.out.println ("\ n final constructed JSON data format:");         system.out.println ( Jo.tostring ());         return jo.tostring ();     }    /**     *  parsing JSON data      *       *  @param  jsonstring json Data string       */    public static void parsejson (string jsonstring)  {         //  with employee as an example, map similar to          jsonobject jB = jsonobject.fromobject (jsonstring);         jsonarray  ja = jb.getjsonarray ("employee");        list< Employee> emplist = new arraylist<employee> ();         //  Loop Add an Employee object (there may be more than one)         for  (int  i = 0; i < ja.size ();  i++)  {             employee employee = new employee ();             employee.setname (Ja.getjsonobject (i). getString ("name"));             employee.setsex (Ja.getJSONObject (i). GetString ("Sex"));             employee.setage ( Ja.getjsonobject (i). GetInt ("Age");Nbsp;           emplist.add (employee);         }        system.out.println ("\ N Convert JSON data to employee object: ");        for  (int i = 0;  i < emplist.size ();  i++)  {             employee emp = emplist.get (i);             system.out.println ("name: "  + emp.getname ()  +  "  sex:  "                     + emp.getsex ()  +  " age: "  + emp.getage ());         }    }    /**      *  @param  aRgs     */    public static void main (String[]  args)  {        // todo auto-generated method  stub        parsejson (Buildjson ());     }}

V. The results of the operation are as follows

650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M01/73/54/wKiom1X6XlKy_1KxAAGX9yuyDew385.jpg "title=" 333. PNG "alt=" wkiom1x6xlky_1kxaagx9yuydew385.jpg "/>

Vi. 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 is much more convenient for constructing beans and parsing beans than Org.json ,Json-lib can directly transform with beans , and Org.json It is not possible to convert the beans directly to each other and need map as a transit, if the bean is converted to JSON data, it is troublesome to first convert the bean to a map and then the map to JSON.

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 the online tool Jsonedit (http://braincast.nl/samples/jsoneditor/) and the other is the plugin json Tree of Eclipse. Analyzer, are very useful, recommended for everyone to use!



This article is from the "Listen to the Rain Hope Eternal" blog, please be sure to keep this source http://yongguang.blog.51cto.com/9153118/1695679

Java parsing JSON

Related Article

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.