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

Source: Internet
Author: User
Tags tojson

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 Org.json.

A detailed approach to constructing and parsing JSON data with Json-lib see my last Post: two ways to construct and parse JSON data using Java (detailed one)

First, introduce

The Org.json package is another package used to Beans,collections,maps,java arrays and XML and JSON to each other, mainly to parse JSON data, which is explained in detail on its website http://www.json.org/. Interested in can go to study.

Second, download the jar dependency pack

can go here to download


Iii. Introduction to the basic methods

Since Org.json cannot be directly converted to the bean, and needs to be relayed through the map, I have written a tool class Jsonhelper for the conversion of JSON to map and bean for convenience.

Package Com.json;
Import Java.lang.reflect.Method;
Import java.text.ParseException;
Import Java.util.HashMap;
Import Java.util.Iterator;
Import Java.util.Map;
Import org.json.JSONException;
Import Org.json.JSONObject; /** * * 1: Convert Javabean to map, Jsonobject * 2: Convert map to Javabean * 3: Convert Jsonobject to map, Javabean * * @author alexia/Public CLA SS Jsonhelper {/** * converts javaBean to map * * @param javaBean * JavaBean * @return Map object/public static map Tomap (Object ja
Vabean) {Map result = new HashMap ();
Method[] methods = Javabean.getclass (). Getdeclaredmethods (); For (method Method:methods) {try {if (Method.getname (). StartsWith (' get ')) {String field = Method.getname (); field = f
Ield.substring (Field.indexof ("get") + 3);
field = Field.tolowercase (). CharAt (0) + field.substring (1);
Object value = Method.invoke (JavaBean, (object[)) null); Result.put (field, NULL = value?) "": value.tostring ());}}
catch (Exception e) {e.printstacktrace ();}}
return result; /** * Converts a JSON object into a map * * @param Jsonobject * JSON Object * @return Map Object * @throws jsonexception */public static Map Tomap (String jsonstring) throws Jsonexce
ption {Jsonobject jsonobject = new Jsonobject (jsonstring);
Map result = new HashMap ();
Iterator iterator = Jsonobject.keys ();
String key = null;
String value = null; 
while (Iterator.hasnext ()) {key = (String) iterator.next (); value = jsonobject.getstring (key); Result.put (key, value);
return result; /** * Converts JavaBean to jsonobject (via map relay) * * @param bean * JavaBean * @return JSON object/public static Jsonobject Tojson (Ob Ject Bean) {return new Jsonobject (Tomap (Bean));/** * Convert Map to JavaBean * * @param javabean * JavaBean * @param data * M AP Data */public static object Tojavabean (Object JavaBean, Map data) {method[] methods = Javabean.getclass (). Getdeclaredmet
Hods (); For (method Method:methods) {try {if (Method.getname (). StartsWith ("set")) {String field = Method.getname (); field = f
Ield.substring (Field.indexof ("set") + 3); field = Field.tolowercase (). CharAt (0) + field.substring (1);
Method.invoke (JavaBean, new object[] {data.get (field)});
The catch (Exception e) {}} return JavaBean; /** * Jsonobject to JavaBean * * @param bean * JavaBean * @return JSON Object * @throws parseexception * JSON Parse exception * @throws JSO Nexception */public static void Tojavabean (Object javabean, String jsonstring) throws ParseException, jsonexception {JSO
Nobject jsonobject = new Jsonobject (jsonstring);
Map map = Tomap (jsonobject.tostring ());
Tojavabean (JavaBean, map); }
}

Iv. Demo sample

This is tested in a few basic common ways

Package Com.json;
Import java.text.ParseException;
Import java.util.ArrayList;
Import Java.util.HashMap;
Import java.util.List;
Import Java.util.Map;
Import Org.json.JSONArray;
Import org.json.JSONException;
Import Org.json.JSONObject; /** * uses Json-lib to construct and parse JSON data * * @author Alexia * * * @date 2013/5/23 * * */public class Orgjsontest {/** * constructs JSON data * * @re Turn * @throws jsonexception */public static String Buildjson () throws Jsonexception {//JSON Format data resolution object Jsonobject JO = NE
W 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);
Converts a map to Jsonarray data jsonarray ja = new Jsonarray ();
Ja.put (MAP1);
System.out.println ("Jsonarray Object Data format:");
System.out.println (Ja.tostring ());
Converts JavaBean to JSON data (requires a map relay) Jsonobject JO1 = Jsonhelper.tojson (employee);
System.out.println ("\ n JSON data format for employee objects only:");
System.out.println (Jo1.tostring ());
Constructs JSON data, including a map and a JSON data jo.put ("map", JA) containing the employee object;
Jo.put ("Employee", jo1.tostring ());
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 * @throws jsonexception * @throws parseexception/public static void
Parsejson (String jsonstring) throws Jsonexception, parseexception {jsonobject Jo = new Jsonobject (jsonstring);
Jsonarray ja = jo.getjsonarray ("map");
System.out.println ("\ n parse JSON data to map:");  System.out.println ("Name:" + ja.getjsonobject (0). getString ("name") + "Sex:" + ja.getjsonobject (0). getString ("sex") + "
Age: "+ ja.getjsonobject (0). GetInt (" Age ")); String Jsonstr = jo.getstring ("employee");
Employee EMP = new Employee ();
Jsonhelper.tojavabean (EMP, JSONSTR);
System.out.println ("\ n parsing JSON data to employee object:");
System.out.println ("Name:" + emp.getname () + "Sex:" + emp.getsex () + "Age:" + emp.getage ());} /** * @param args * @throws jsonexception * @throws parseexception/public static void Main (string[) args) throws Jsonex Ception, ParseException {//TODO auto-generated Method Stub Parsejson (Buildjson ());}

The results of the operation are as follows


V. Comparison with Json-lib

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 two) of the relevant knowledge, I hope to help you!

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.