Using JSON for data passing in Java

Source: Internet
Author: User

Recently working on a Java servlet-based Web application and corresponding Anroid application client development.

In this context, the use of JSON objects to manipulate formatted data in terms of interface access and data transfer is used: JSON strings are used on the server side to pass data, and JSON is used by the Web front end or Android client to parse the received data.
First, the use of JSON in Java requires the introduction of the Org.json package (click here to download the corresponding JAR package!). ), and introduce the appropriate JSON class in the program:

Import Org.json.JSONArray; Import org.json.JSONException; Import Org.json.JSONObject;

Second, in the server-side servlet class, you can use the following methods to collect data and generate the appropriate JSON string \

 //  Declare a hash object and add data  Map params  = new   HashMap ();  params . Put ( username   "  params . Put ( user_json   "  //  Declare Jsonarray object and enter a JSON string  Jsonarray array = jsonarray.fromobject (params   

JSON strings can be parsed directly in the Web front-end via JavaScript, and in the case of Android clients, a JSON class is used to parse the string:

//@description: Parses the data and data objects contained in a string based on the JSON string received//the received JSON stringString result ="[{\ "username\": \ "Your name\", \ "user_json\": {\ "username\": \ "Your name\", \ "nickname\": \ "Your Nickname\"}}]";//to generate a JSON object from a stringJsonarray resultarray =NewJsonarray (Result); Jsonobject Resultobj= Resultarray.optjsonobject (0);//Get data itemString username = resultobj.getstring ("username");//Get Data ObjectJsonobject user = Resultobj.getjsonobject ("User_json"); String Nickname= User.getstring ("Nickname");

In fact, the main concern is the conversion between the following centralized data types:

1. String conversion to JSON object

import Org.json.jsonarray;import org.json.jsonexception;import org.json.JSONObject;//do not forget to add the JSON package Oh! Public classStringtojson { Public Static voidMain (string[] args) throws jsonexception{System. out. println ("ABC"); //Defining JSON StringsString Jsonstr ="{\ "id\": 2,"+"\ "title\": \ "JSON title\","+"\ "Config\": {"+"\ "Width\":"+"\ "Height\":"+"}, \ "Data\": ["+"\ "Java\", \ "javascript\", \ "Php\""+"]}"; //convert to a Jsonobject objectJsonobject jsonobj =NewJsonobject (JSONSTR); //getting data from a Jsonobject objectJavaBean Bean =NewJavaBean (); //gets the int type data according to the property name;Bean.setid (Jsonobj.getint ("ID")); //gets the string data based on the property name;Bean.settitle (Jsonobj.getstring ("title")); //get the Jsonobject class by property nameJsonobject config = jsonobj.getjsonobject ("Config"); Bean.setwidth (Config.getint ("width")); Bean.setheight (Config.getint ("Height")); //get Jsonarray Array by property nameJsonarray data = Jsonobj.getjsonarray ("Data");  for(intindex =0, length = Data.length (); Index < length; index++) {            //here in Org.json.JSONArray object actually did not find ToArray method, ask you to give a solution ah! //bean.setlanguages (string[]);        }            }}classjavabean{Private intID; PrivateString title; Private intwidth; Private intheight; Privatestring[] languages; //the setup and accessors are omitted here}

2. JSON object converted to string string

 Public Static voidMain (string[] args) throws Jsonexception {//Create a Jsonobject objectJsonobject JSON =NewJsonobject (); //adding data to the JSONJson.put ("username","Wanglihong"); Json.put ("Height",12.5); Json.put (" Age", -); //Create a Jsonarray array and add the JSON to the arrayJsonarray array =NewJsonarray ();                Array.put (JSON); //Convert to StringString Jsonstr =array.tostring (); System. out. println (JSONSTR); }

The resulting output is: [{"username": "Wanglihong", "height": 12.5, "Age": 24}]

3. set conversion to Jsonarray object

 Public Static voidMain (string[] args) throws jsonexception{//Initialize the ArrayList collection and add datalist<string> list =NewArraylist<string>(); List.add ("username"); List.add (" Age"); List.add ("Sex"); //initializes the HashMap collection and adds an arrayMap map =NewHashMap (); Map.put ("BookName","CSS3 Combat"); Map.put (" Price",69.0); //Initialize the Jsonarray object and add dataJsonarray array =NewJsonarray ();        Array.put (list);                Array.put (map); //The resulting JSON string is: [[' Username ', ' age ', ' sex '],{' price ': ' bookname ': ' CSS3 Combat '}]}

Using JSON for data passing 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.