Two ways to construct and parse JSON data in Java--json-lib

Source: Internet
Author: User

Transferred from: http://www.cnblogs.com/lanxuezaipiao/archive/2013/05/23/3096001.html

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

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

2. Map collection into JSON method

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

3. Bean converted to JSON code

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

4. Convert arrays into JSON code

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

5. Conversion of general data into JSON code

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

6. Beans conversion to JSON code

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

Iv. Demonstration Examples

Here are some basic common methods for testing

Package Com.json;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;/** * Constructs and parses JSON data using Json-lib * * @author Alexia * @date 2013/5/        */public class Jsontest {/** * constructs JSON data * * @return */public static String Buildjson () {        JSON-formatted data parsing object Jsonobject Jo = new Jsonobject ();        The following 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", "23");        map<string, string> map2 = new hashmap<string, string> ();        Map2.put ("name", "Edward");        Map2.put ("Sex", "male");        Map2.put ("Age", "24");        list<map> list = new arraylist<map> ();        List.add (MAP1);        List.add (MAP2);        Employee Employee = new Employee ();        Employee.setname ("Wjl"); EmployeE.setsex ("female");        Employee.setage (24);        Convert map to Jsonarray data jsonarray ja1 = Jsonarray.fromobject (MAP1);        Convert list to Jsonarray data Jsonarray ja2 = Jsonarray.fromobject (list);        Convert bean 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 ());        System.out.println (Ja3.tostring ());        Constructs JSON data, including a map and an employee object Jo.put ("map", JA1);        Jo.put ("Employee", JA2);        System.out.println ("\ n final constructed JSON data format:");        System.out.println (Jo.tostring ());    return jo.tostring ();  }/** * Parse 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 Employee object (may have multiple) 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"));        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 ()); }}

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!

Two ways to construct and parse JSON data in Java--json-lib

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.