Parse and construct a json string using JSONObject and JSONArray.

Source: Internet
Author: User

Parse and construct a json string using JSONObject and JSONArray.

The JSON-lib package (the two most critical classes are JSONObject and JSONArray) completes the construction of json and the use of some basic methods.

Differences:

① The string constructed by JSONObject is in key: value format. Multiple key-value pairs are connected by commas;

② The string constructed by JSONArray is in the array format ([array1, array2,...]).

Package download link to use: http://pan.baidu.com/s/1o7MZ8X8

1. Use of JSONObject.

(1) Two construction methods for JSON strings:

① Use a Java object; ② use a Map set.

Step 1: first create a Java project and import the dependency package;

Step 2: create two test classes:

Teacher. java

package com.snnu.json;import java.util.List;public class Teacher {    private String name;    private String sex;    private int age;    private List<Transport> myTool;            public Teacher(){            }        public Teacher(String name,String sex,int age,List<Transport> myTool){        this.name = name;        this.sex = sex;        this.age = age;        this.myTool = myTool;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getSex() {        return sex;    }    public void setSex(String sex) {        this.sex = sex;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }    public List<Transport> getMyTool() {        return myTool;    }    public void setMyTool(List<Transport> myTool) {        this.myTool = myTool;    }}

Transport. java

package com.snnu.json;public class Transport {        private String name;    private float price;        public Transport(){            }        public Transport(String name,float price){        this.name = name;        this.price = price;    }            public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public float getPrice() {        return price;    }    public void setPrice(float price) {        this.price = price;    }                }

Step 3: Write the main method

Method 1:

Package com. snnu. json; import java. util. arrayList; import java. util. list; import net. sf. json. JSONObject; public class Demo_creajsonFromObject {// use a java Object to generate a json string public JSONObject createJsonFromObject (object Object object) {return JSONObject. fromObject (object);} public static void main (String [] args) {// TODO Auto-generated method stub Demo_creajsonFromObject demo = new Demo_creajsonFromObject (); teacher t = new Teacher (); t. setName ("Zhang San"); t. setSex ("male"); t. setAge (21); Transport bike = new Transport ("bicycle", 267); Transport motorcycle = new Transport ("motorcycle", 3267 ); transport car = new Transport ("car", 100000); List <Transport> tools = new ArrayList <Transport> (); tools. add (bike); tools. add (motorcycle); tools. add (car); t. setMyTool (tools); JSONObject ob = demo. createJsonFromObject (t); System. out. println (ob );}}

The generated json string is:

{"Age": 21, "myTool": [{"name": "bicycle", "price": 267 },{ "name": "motorcycle ", "price": 3267 },{ "name": "car", "price": 100000}], "name": "Zhang San", "sex": "male "}

 

Method 2:

Package com. snnu. json; import java. util. hashMap; import java. util. map; import net. sf. json. JSONObject; public class Demo_creajsonFromMap {// use the map set to generate the json String public JSONObject createJsonFromMap (Map <String, String> map) {JSONObject jsob = new JSONObject (); jsob. putAll (map); return jsob;} public static void main (String [] args) {// TODO Auto-generated method stub Demo_creajsonFromMap demo = new Demo_creajsonFromMap (); Map <String, string> mmap = new HashMap <String, String> (); mmap. put ("name", "Zhang San"); mmap. put ("sex", "male"); mmap. put ("age", "21"); JSONObject ob = demo. createJsonFromMap (mmap); System. out. println (ob );}}

The generated json string is:

{"Sex": "male", "name": "Zhang San", "age": "21 "}

(2) Examples of three common JSONObject methods.

Package com. snnu. json; import java. util. arrayList; import java. util. list; import net. sf. json. JSONObject; public class MethodTest {// put method: Insert a node into a json file. If the node already exists, the value of the node will be replaced with public JSONObject testPut () {JSONObject jo1 = new JSONObject (); jo1.put ("a", "1"); jo1.put ("B", "2"); jo1.put ("c ", "3"); Transport bike = new Transport ("bike", 200); jo1.put ("d", bike ); list <String> list = new ArrayList <String> (); list. add ("one"); list. add ("two"); list. add ("three"); jo1.put ("e", list); jo1.put ("a", "100"); return jo1 ;}// accumulate method: you can accumulate values under the same key. If the value corresponding to the key has a value, it is accumulated in the form of an array; otherwise, it is equivalent to the put method public JSONObject testAccumulate () {JSONObject jo2 = new JSONObject (); jo2.put ("a", "1"); jo2.put ("B", "2"); jo2.put ("c ", "3"); jo2.accumulate ("c", "300"); Transport bike = new Transport ("bike", 200); jo2.accumulate ("c", bike ); list <String> list = new ArrayList <String> (); list. add ("one"); list. add ("two"); list. add ("three"); jo2.accumulate ("c", list); jo2.put ("d", "4"); return jo2 ;} // basically consistent with the put method public JSONObject testElement () {JSONObject jo3 = new JSONObject (); jo3.put ("a", "1"); jo3.put ("B ", "2"); jo3.put ("c", "3"); jo3.element ("c", "300"); return jo3 ;} public static void main (String [] args) {// TODO Auto-generated method stub MethodTest test = new MethodTest (); System. out. println ("Use the put Method of JSONObject" + test. testPut (); System. out. println ("Use the accumulate method of JSONObject" + test. testAccumulate (); System. out. println ("use the element method of JSONObject" + test. testElement ());}}

 

① The format of the json string output by the put method is as follows:

{    "a": "100",    "b": "2",    "c": "3",    "d": {        "name": "bike",        "price": 200    },    "e": [        "one",        "two",        "three"    ]}

② The result of formatting the json string output by the accumulate method is:

{    "a": "1",    "b": "2",    "c": [        "3",        "300",        {            "name": "bike",            "price": 200        },        [            "one",            "two",            "three"        ]    ],    "d": "4"}

③ The format result of the json string output by the element method is:

{    "a": "1",    "b": "2",    "c": "300"}

Ii. Use of JSONArray

(1) Basic usage:

Package com. snnu. json; import net. sf. json. JSONArray; import net. sf. json. JSONObject; public class demo_JsonArray {public JSONObject testJsonArray () {JSONObject ob = new JSONObject (); JSONArray ja = new JSONArray (); ja. add ("1"); ja. add ("2"); ja. add ("3"); ja. add ("4"); ja. add ("5"); ob. put ("array", ja); return ob;} public static void main (String [] args) {// TODO Auto-generated method stub demo_JsonArray djs = new demo_JsonArray (); system. out. println ("use of JSONArray:" + djs. testJsonArray ());}}

Format the output string:

{    "array": [        "1",        "2",        "3",        "4",        "5"    ]}

Iii. Integrated instances

Package com. snnu. json; import net. sf. json. JSONArray; import net. sf. json. JSONObject; public class demo_testJson {public JSONObject test () {JSONObject jo = new JSONObject (); jo. put ("name", "Zhang San"); jo. put ("sex", "f"); jo. put ("age", 21); Transport bike = new Transport ("bike", 250); jo. put ("extra", bike); Transport car = new Transport ("car", 10000); jo. accumulate ("extra", car); Transport motor = new Transport ("motor", 3000); jo. accumulate ("extra", motor); System. out. println (jo); // obtain the corresponding value String value = jo based on the key value (extra. getString ("extra"); System. out. println (value); // converts a string to JSONArray jsar = JSONArray. fromObject (value); String str_2 = String. valueOf (jsar. get (1); System. out. println (str_2); // converts a string to JSONObject jsob = JSONObject. fromObject (str_2); System. out. println ("name:" + jsob. getString ("name"); System. out. println ("Price:" + jsob. getString ("price"); System. out. println ("-----------------------------------------------------------------------------"); return jo;} public static void main (String [] args) {// TODO Auto-generated method stub demo_testJson dtj = new demo_testJson (); System. out. println ("Comprehensive test:" + dtj. test ());}}

Output result:

{"Name": "Zhang San", "sex": "f", "age": 21, "extra": [{"name": "bike ", "price": 250 },{ "name": "car", "price": 10000 },{ "name": "motor", "price ": 3000}]} [{"name": "bike", "price": 250 },{ "name": "car", "price": 10000 }, {"name": "motor", "price": 3000}] {"name": "car", "price": 10000} name: car price: 10000 --------------------------------------------------------------------------- Comprehensive Test: {"name": "Zhang San", "sex": "f", "age": 21, "extra ": [{"name": "bike", "price": 250 },{ "name": "car", "price": 10000 },{ "name ": "motor", "price": 3000}]}

 

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.