Two ways to construct and parse JSON data using Java (detailed one) _java

Source: Internet
Author: User

JSON (JavaScript Object notation) is a lightweight data interchange format that uses a completely language-independent text format and is an ideal data interchange format. Also, JSON is the native format of JavaScript, which means that processing JSON data in JavaScript does not require any special APIs or toolkits.

Many of the JSON constructs and parsing tools in Java are published on the www.json.org, where Org.json and json-lib are simpler, and they are used almost but somewhat differently. The following is an example of how to construct and parse JSON data using Json-lib.

A detailed approach to constructing and parsing JSON data with Org.son see my next post: two ways to construct and parse JSON data using Java (detail two)

First, introduce

The Json-lib package is a Beans,collections,maps,java arrays and XML and JSON-converted packages that are used primarily to parse JSON data and are explained in detail on its website http://www.json.org/. Interested in can go to study.

Second, download jar dependencies: can go here to download


Iii. Introduction to the basic methods

1. List collection converted to JSON method

List List = new ArrayList ();
List.add ("a");
List.add ("second");

2. Map collection converted to 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];}");

3. Bean converted to JSON code

 
 

4. Convert array into JSON code

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

5. Convert general data into JSON code

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

6. Convert Beans 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);

Iv. Demo sample

This is tested in a few basic common ways

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; 
/** * uses Json-lib to construct and parse JSON data * * @author Alexia * * * @date 2013/5/23 * * */public class Jsontest {/** * constructs 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", "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); Converts a list to Jsonarray data JSOnarray ja2 = jsonarray.fromobject (list);
Converts the 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) {//To employee For example resolution, MA
P resembles jsonobject jb = Jsonobject.fromobject (jsonstring);
Jsonarray ja = Jb.getjsonarray ("employee");
list<employee> emplist = new arraylist<employee> (); Loop Add Employee object (there may be 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 an 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 results of the operation are as follows


V. Comparison with Org.json

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

1. Org.json is much lighter than Json-lib, the former does not rely on any other jar packs, and the latter relies on ezmorph and Commons components such as Lang, logging, beanutils, collections, etc.

2. Json-lib is more convenient than org.json to construct beans and parse beans, json-lib can convert directly to and from the bean, and Org.json cannot convert directly to the bean and need map as a relay, and if you convert the bean to JSON data, you first need to transform the bean to M The AP then turns the map into JSON, which is more cumbersome.

In short, or that sentence-the best for their own, we have to select on demand to use which method to resolve. Finally, we introduce two tools for parsing JSON data: One is the online tool JSON Edit (http://braincast.nl/samples/jsoneditor/); the other is Eclipse's plug-in json tree Analyzer, are very useful, recommended for everyone to use!

The above is a small series to introduce the use of Java construction and parsing JSON data two methods (detailed one), I hope to help!

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.