Home > Java > javaTutorial > The use of json construction and methods by JSON-lib package

The use of json construction and methods by JSON-lib package

零下一度
Release: 2017-06-27 10:34:26
Original
1418 people have browsed it

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.

The difference between the two:

①The string constructed by JSONObject is in the form of key-value pairs (key:value), and multiple key-value pairs are connected with English commas;

②JSONArray The constructed string is in the form of an array ([array1, array2,...]).

Required package download link:

1. Use of JSONObject.

(1) Two construction methods for JSON strings:

① Use Java objects; ② Use Map collections.

Step 1: First create a new Java project and import dependency packages;

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;
    }

}
Copy after login

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;
    }
    
    
    
    
}
Copy after login

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 {// 利用java对象生成json字符串public JSONObject createJsonFromObject(Object object) {return JSONObject.fromObject(object);
    }public static void main(String[] args) {// TODO Auto-generated method stubDemo_creajsonFromObject demo = new Demo_creajsonFromObject();

        Teacher t = new Teacher();
        t.setName("张三");
        t.setSex("男");
        t.setAge(21);

        Transport bike = new Transport("自行车", 267);
        Transport motorcycle = new Transport("摩托车", 3267);
        Transport car = new Transport("小汽车", 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);

    }

}
Copy after login

Generate The json string is:

{
    "age": 21,
    "myTool": [
        {
            "name": "自行车",
            "price": 267
        },
        {
            "name": "摩托车",
            "price": 3267
        },
        {
            "name": "小汽车",
            "price": 100000
        }
    ],
    "name": "张三",
    "sex": "男"
}
Copy after login

Method 2:

package com.snnu.json;import java.util.HashMap;import java.util.Map;import net.sf.json.JSONObject;public class Demo_creajsonFromMap {//使用map集合生成json字符串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 stubDemo_creajsonFromMap demo=new Demo_creajsonFromMap();
        
        Map<String,String> mmap=new HashMap<String,String>();
        mmap.put("name", "张三");
        mmap.put("sex", "男");
        mmap.put("age", "21");
        
        JSONObject ob=demo.createJsonFromMap(mmap);
        System.out.println(ob);
        
    }

}
Copy after login

Generated json The string is:

{"sex": "男","name": "张三","age": "21"}
Copy after login

(2) Examples of three common methods of JSONObject.

package com.snnu.json;import java.util.ArrayList;import java.util.List;import net.sf.json.JSONObject;public class MethodTest {//put方法:在一个json中插入一个节点,若该节点已存在,则该节点的值将会被替换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方法:可以在同一个key下累积值,若key对应的value有值,则以数组形式累积;否则相当于put方法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;
    }    
    //与put方法基本一致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 stubMethodTest test=new MethodTest();
        System.out.println("JSONObject的put方法使用"+test.testPut());
        System.out.println("JSONObject的accumulate方法使用"+test.testAccumulate());
        System.out.println("JSONObject的element方法使用"+test.testElement());
        
    }

}
Copy after login

①The put method outputs the json string format and the result is:

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

②The accumulate method outputs the json string format The formatted result is:

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

③The element method outputs the json string formatted result:

{"a": "1","b": "2","c": "300"}
Copy after login

2. 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 stubdemo_JsonArray djs=new demo_JsonArray();
        System.out.println("JSONArray的使用:"+djs.testJsonArray());
        
    }

}
Copy after login

Format the output string:

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

3. Comprehensive example

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", "张三");
        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);        //根据key值(为extra)取对应的valueString value=jo.getString("extra");
        System.out.println(value);        //将字符串转化为JSONArrayJSONArray jsar=JSONArray.fromObject(value);
        String str_2=String.valueOf(jsar.get(1));
        System.out.println(str_2);        //将字符串转化为JSONObjectJSONObject jsob=JSONObject.fromObject(str_2);
        System.out.println("名称:"+jsob.getString("name"));
        System.out.println("价钱:"+jsob.getString("price"));
        
        System.out.println("-------------------------------分界线-------------------------------------------");        return jo;
        
    }public static void main(String[] args) {// TODO Auto-generated method stubdemo_testJson dtj=new demo_testJson();
        System.out.println("综合测试:"+dtj.test());
    }

}
Copy after login

The output result is:

{"name":"张三","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}
名称:car
价钱:10000
-------------------------------分界线-------------------------------------------综合测试:{"name":"张三","sex":"f","age":21,"extra":[{"name":"bike","price":250},{"name":"car","price":10000},{"name":"motor","price":3000}]}
Copy after login

The above is the detailed content of The use of json construction and methods by JSON-lib package. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template