Two ways to construct and parse JSON data in Java two--org.json

Source: Internet
Author: User
Tags tojson

Transferred from: http://www.cnblogs.com/lanxuezaipiao/archive/2013/05/24/3096437.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 is an example of how to construct and parse JSON data using Org.json.

To construct and parse JSON data in Json-lib, see my previous blog post: Two approaches to Java construction and parsing JSON data

First, Introduction

The Org.json package is another package used to Beans,collections,maps,java arrays and XML and JSON to convert the JSON data, which is explained in detail on its website http://www.json.org/. Interested to be able to study.

Ii. Download the jar dependency package

can go here to download

Iii. Introduction to the basic methods

Since the Org.json cannot be converted directly to the bean and needs to be brokered through a map, I have written a tool class Jsonhelper here to convert JSON to map and bean.

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 class Jsonhelpe    R {/** * convert JavaBean to map * * @param javaBean * JavaBean * @return Map Object */        public static map Tomap (Object javaBean) {map result = new HashMap ();        Method[] methods = Javabean.getclass (). Getdeclaredmethods ();                    for (Method method:methods) {try {if (Method.getname (). StartsWith ("get")) {                    String field = Method.getname ();                    field = Field.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; /** * Convert JSON object to map * * @param jsonobject * JSON Object * @return Map Object * @throws JSON Exception */public static Map Tomap (String jsonstring) throws Jsonexception {Jsonobject jsonobject = new J                Sonobject (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;     }/** * Convert JavaBean to Jsonobject (via map) * * @param bean * JavaBean * @return JSON object */public static jsonobject ToJSON (Object 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 ().        Getdeclaredmethods ();                    for (Method method:methods) {try {if (Method.getname (). StartsWith ("set")) {                    String field = Method.getname ();                    field = Field.substring (Field.indexof ("set") + 3);                    field = Field.tolowercase (). CharAt (0) + field.substring (1);                Method.invoke (JavaBean, new object[] {data.get (field)});    }} catch (Exception e) {}} return JavaBean; }/** * Jsonobject to JavaBean * * @param bean * JavaBean * @return JSON object * @throws P Arseexception * JSOn parsing exception * @throws jsonexception */public static void Tojavabean (Object javabean, String jsonstring)            Throws ParseException, jsonexception {jsonobject jsonobject = new Jsonobject (jsonstring);                Map map = Tomap (jsonobject.tostring ());    Tojavabean (JavaBean, map); }}
Iv. Demonstration Examples

Here are some basic common methods for testing

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;/** * Constructs and parses JSON data using Json-lib * * @author Alexia * @date 2013/5/23 * */public class Orgjsontest {/ * * Constructs JSON data * * @return * @throws jsonexception */public static String Buildjson () throws Jsone        Xception {//JSON Format 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 ja = new Jsonarray ();        Ja.put (MAP1);        System.out.println ("Jsonarray Object Data format:");        System.out.println (Ja.tostring ());        Convert JavaBean to JSON data (requires map relay) Jsonobject JO1 = Jsonhelper.tojson (employee);        System.out.println ("\ n only JSON data format with employee object:");        System.out.println (Jo1.tostring ());        Constructs JSON data, including a map and a JSON data jo.put ("map", JA) with 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 * @throw s 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 into map:"); System.out.println ("Name:" + ja.getjsonobject (0). getString ("name") + "Sex:" + ja.getjsonobject (0). getstr        ing ("sex") + "Age:" + ja.getjsonobject (0). GetInt ("Age"));        String jsonstr = jo.getstring ("employee");        Employee EMP = new Employee ();        Jsonhelper.tojavabean (EMP, JSONSTR);        System.out.println ("\ nthe JSON data parsed as employee object:");    System.out.println ("Name:" + emp.getname () + "Sex:" + emp.getsex () + "Age:" + emp.getage ()); }/** * @param args * @throws jsonexception * @throws parseexception */public static void main (Stri     Ng[] args) throws Jsonexception, ParseException {//TODO auto-generated Method Stub Parsejson (Buildjson ()); }}

The operation results are as follows

V. Comparison with Json-lib

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 two--org.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.