Two ways to construct and parse JSON data in Java

Source: Internet
Author: User
Tags tojson

First, Introduction

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, on its official website http://www.json.org/ Have a detailed explanation, interested can go 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.

PackageCom.json;ImportJava.lang.reflect.Method;ImportJava.text.ParseException;ImportJava.util.HashMap;ImportJava.util.Iterator;ImportJava.util.Map;ImportOrg.json.JSONException;ImportOrg.json.JSONObject;/*** * 1: Convert Javabean to map, Jsonobject * 2: Convert map to Javabean * 3: Convert Jsonobject to map, Javabean * *@authorAlexia*/PublicClassJsonhelper {/*** Convert JavaBean to map * *@paramJavaBean * JavaBean *@returnMap Object*/PublicStaticMap Tomap (Object javaBean) {Map result =NewHashMap (); 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 ();} }ReturnResult }/*** Convert JSON object to map * *@paramJsonobject * JSON Object *@returnMap Object *@throwsJsonexception*/PublicStatic Map Tomap (String jsonstring)Throwsjsonexception {Jsonobject Jsonobject =NewJsonobject (jsonstring); Map result =NewHashMap (); 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); }ReturnResult }/*** Convert JavaBean to Jsonobject (transfer via map) * *@paramBean * JavaBean *@returnJSON object*/PublicStaticJsonobject ToJSON (Object Bean) {ReturnNewJsonobject (Tomap (bean)); }/*** Convert Map to JavaBean * *@paramJavaBean * JavaBean *@paramData * Map*/PublicStaticObject 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,NewObject[] {data.get (field)}); } }Catch(Exception e) { } }ReturnJavaBean }/*** Jsonobject to JavaBean * * @param  Bean * JavaBean *  JSON object *  @throws  ParseException * 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

PackageCom.json;ImportJava.text.ParseException;ImportJava.util.ArrayList;ImportJava.util.HashMap;ImportJava.util.List;ImportJava.util.Map;ImportOrg.json.JSONArray;ImportOrg.json.JSONException;ImportOrg.json.JSONObject;/*** Construct and parse JSON data using Json-lib * *@authorAlexia * @date 2013/5/23 **/PublicClassorgjsontest {/*** Construct JSON Data * *@return*@throwsJsonexception*/PublicStatic String Buildjson ()Throwsjsonexception {//JSON-formatted data parsing object Jsonobject Jo =NewJsonobject ();//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 =NewEmployee (); Employee.setname ("Wjl"); Employee.setsex ("female"); Employee.setage (24);//Convert map to jsonarray data jsonarray ja =NewJsonarray (); 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 the JSON data format for employee objects:"); System.out.println (Jo1.tostring ());//Constructs JSON data, including a map and a JSON data jo.put with an Employee object ("Map", JA); Jo.put ("Employee", jo1.tostring ()); System.out.println ("\ n final constructed JSON data format:"); System.out.println (Jo.tostring ());ReturnJo.tostring (); }/*** Parse JSON data * *@paramjsonstring * JSON Data String *@throwsJsonexception *@throwsParseException*/PublicStaticvoid Parsejson (String jsonstring)ThrowsJsonexception, parseexception {jsonobject Jo =NewJsonobject (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). getString ("sex") + "Age:" + ja.getjsonobject (0). GetInt (' age ')); String jsonstr = jo.getstring ("Employee"); Employee emp =NewEmployee (); Jsonhelper.tojavabean (EMP, JSONSTR); System.out.println ("\ nthe JSON data resolves to the 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 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 is much more convenient for constructing beans and parsing beans than Org.json,Json-lib can directly transform with beans, and Org.json can not directly with the bean to convert to and need map as a transit, if the bean into JSON data, first need to convert the bean to map and then the map to JSON, more trouble.


Ext.: http://www.cnblogs.com/lanxuezaipiao/archive/2013/05/24/3096437.html

Two ways to construct and parse JSON data in Java

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.