Java Operation JSON

Source: Internet
Author: User

First, JSON syntax

Json:javascript Object Notation (JavaScript object Notation), JSON is the syntax for storing and exchanging textual information. XML-like, but smaller, faster, and easier to parse than XML.
The writing format for JSON data is: name/value pairs.
Name/value pairs include the field name (in double quotation marks), followed by a colon, and then the value:

"firstName""John"

The JSON array is written in square brackets:
An array can contain multiple objects:

{    "employees[        { "firstName":"John" , "lastName":"Doe" },        { "firstName":"Anna" , "lastName":"Smith" },        { "firstName":"Peter" , "lastName":"Jones" }     ]}
Ii. introduction of Gson

Gson is a Java class library provided by Google for mapping between Java objects and JSON data. You can turn a JSON string into a Java object, or vice versa. Download jar Package: http://download.csdn.net/detail/yang_xing_/8363795. Create a new Java project in Eclipse and introduce Gson-2.2.4.jar. Create a Employee.json file under the project root directory:

{    "Department":"Design",    "Employees":[{"firstName":"Bill" , "lastName":"Gates "}, {" firstName":" George " ,"lastName":" Bush " }, {"firs Tname":Thomas" , "lastName":"Carter" }]}
Second, read JSON

First create a JSON parser, then create a Jsonobject object, and then call the Get method to access the property values:

Package Ucas. JSON. Test;Import Java. IO. File;Import Java. IO. FileNotFoundException;Import Java. IO. FileReader;Importcom. Google. Gson. Jsonioexception;Importcom. Google. Gson. Jsonobject;Importcom. Google. Gson. Jsonparser;Importcom. Google. Gson. Jsonsyntaxexception;public class Jsontest {public static void main (string[] args) {try {jsonparser jparser = new JsonP Arser ();Jsonobject jobject = (jsonobject) jparser. Parse(New FileReader ("Employee.json"));System. out. println(Jobject. Get("department"). getasstring());System. out. println(Jobject. Get("Employees"));} catch (Jsonioexception e) {E. Printstacktrace();} catch (Jsonsyntaxexception e) {E. Printstacktrace();} catch (FileNotFoundException e) {E. Printstacktrace();}    }}

Output Result:

design[{"firstName":"Bill","lastName":"Gates"},{"firstName":"George","lastName":"Bush"},{"firstName":"Thomas","lastName":"Carter"}]

You can see that the "Employees" attribute is an array, converted to Jsonarray, and then recycled:

Package Ucas. JSON. Test;Import Java. IO. File;Import Java. IO. FileNotFoundException;Import Java. IO. FileReader;Importcom. Google. Gson. Jsonarray;Importcom. Google. Gson. Jsonioexception;Importcom. Google. Gson. Jsonobject;Importcom. Google. Gson. Jsonparser;Importcom. Google. Gson. Jsonsyntaxexception;public class Jsontest {public static void main (string[] args) {try {jsonparser jparser = new JsonP Arser ();Jsonobject jobject = (jsonobject) jparser. Parse(New FileReader ("Employee.json"));System. out. println(Jobject. Get("department"). getasstring());Jsonarray jarray= (Jsonarray) jobject. Get("Employees");for (int i =0; i < jarray.size (); i++) {System. out. println("-----------");Jsonobject jobject2= (jsonobject) Jarray. Get(i);System. out. println("ID:"+jobject2. Get("id"). getasstring());System. out. println("FirstName:"+jobject2. Get("FirstName"). getasstring());System. out. println("LastName:"+jobject2. Get("LastName"). getasstring());}} catch (Jsonioexception e) {E. Printstacktrace();} catch (Jsonsyntaxexception e) {E. Printstacktrace();} catch (FileNotFoundException e) {E. Printstacktrace();}    }}

Output Result:

design-----------id:1firstName:BilllastName:Gates-----------id:1firstName:GeorgelastName:Bush-----------id:3firstName:ThomaslastName:Carter
Third, create JSON

To create a JSON object, add an attribute using the AddProperty method, add an object using the Add method, for example:

Import Java. IO. BufferedReader;Import Java. IO. BufferedWriter;Import Java. IO. File;Import Java. IO. FileOutputStream;Import Java. IO. IOException;Import Java. IO. InputStream;Import Java. IO. OutputStreamWriter;Importcom. Google. Gson. Jsonarray;Importcom. Google. Gson. Jsonobject;public class JsonDemo2 {public static void main (string[] args) {//Create JSON data jsonobject Jsonobject = new Jsonobject ();Jsonobject. AddProperty("Cat","It");Jsonarray Jarray = new Jsonarray ();Jsonobject lan1 = new Jsonobject ();Lan1. AddProperty("id",1);Lan1. AddProperty("Name","Java");Lan1. AddProperty("IDE","Eclipse");Jarray. Add(LAN1);Jsonobject lan2 = new Jsonobject ();Lan2. AddProperty("id",2);Lan2. AddProperty("Name","C + +");Lan2. AddProperty("IDE","VC6.0");Jarray. Add(lan2);Jsonobject lan3 = new Jsonobject ();Lan3. AddProperty("id",3);Lan3. AddProperty("Name","C #");Lan3. AddProperty("IDE","Visual Studio");Jarray. Add(LAN3);Jsonobject lan4 = new Jsonobject ();Lan4. AddProperty("id",4);Lan4. AddProperty("Name","Swift");Lan4. AddProperty("IDE","Xcode");Jarray. Add(LAN4);Jsonobject. Add("Languages", Jarray);Jsonobject. AddProperty("Pop", true);System. out. println(Jsonobject);File Jsonfile = new file ("Test.json");try {Jsonfile. CreateNewFile();FileOutputStream fos = new FileOutputStream (jsonfile);OutputStreamWriter osq = new OutputStreamWriter (FOS);BufferedWriter BFW = new BufferedWriter (OSQ);BfW. Write(Jsonobject. toString());BfW. Close();Osq. Close();Fos. Close();} catch (IOException e) {//TODO auto-generated catch block E. Printstacktrace();}    }}

This will generate a Test.json file in the project root directory:

{"Cat":"It","Languages":[{"ID":1,"name":"haha","IDE":"eclipse\n"},{"ID":2,"name":"C + +","IDE":"VC6.0"},{"ID":3,"name":"C #","IDE":"Visual Studio"},{"ID":4,"name":"Swift","IDE":"Xcode"}],"Pop":true}

Summarize:

    1. JSON introduction and syntax can refer to the JSON website http://www.json.org/and web tutorial JSON tutorial
    2. There are many libraries for manipulating JSON, so you can choose to learn.

Java Operation JSON

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.