Json字符串轉對象和轉List集合操作(json-lib版本) Json字符串轉對象和轉List集合操作(alibabab版本)

Json字符串轉對象和轉List集合操作(json-lib版本)

Json是當前開發用得最多基於JavaScript語言的輕量級的數據交換格式,總結一下常用轉換格式的方法,以便日後使用方便


以下爲 json-lib包各種 JSON 轉換的方法總結:

1. 所需引入的第三方包:

                <dependency>
			<groupId>commons-beanutils</groupId>
			<artifactId>commons-beanutils</artifactId>
			<version>1.9.3</version>
		</dependency>

		<dependency>
			<groupId>commons-collections</groupId>
			<artifactId>commons-collections</artifactId>
			<version>3.2.1</version>
		</dependency>

		<dependency>
			<groupId>commons-lang</groupId>
			<artifactId>commons-lang</artifactId>
			<version>2.6</version>
		</dependency>

		<dependency>
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging</artifactId>
			<version>1.2</version>
		</dependency>
		<dependency>
			<groupId>xom</groupId>
			<artifactId>xom</artifactId>
			<version>1.2.5</version>
		</dependency>
		<dependency>
			<groupId>net.sf.ezmorph</groupId>
			<artifactId>ezmorph</artifactId>
			<version>1.0.4</version>
		</dependency>

		<dependency>
			<groupId>net.sf.json-lib</groupId>
			<artifactId>json-lib</artifactId>
			<version>2.4</version>
			<classifier>jdk13</classifier>
		</dependency>

2. 對象User類

package com.lmx.demo;

public class User
{

    private String cId;

    private String uName;

    private String pwd;

    public  User(){
       
    }
    public  User(String cId, String uName, String pwd){
        
        this.cId = cId;
        this.uName = uName;
        this.pwd = pwd;
        
    }
    
    public String getcId()
    {
        return cId;
    }

    public void setcId(String cId)
    {
        this.cId = cId;
    }

    public String getuName()
    {
        return uName;
    }

    public void setuName(String uName)
    {
        this.uName = uName;
    }

    public String getPwd()
    {
        return pwd;
    }

    public void setPwd(String pwd)
    {
        this.pwd = pwd;
    }

}

3. Json各類轉換

package com.lmx.demo;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.xml.XMLSerializer;


/**
 * json-lib
 * 
 * @author LMX
 */
public class SfJson
{

    /**
     * 1. json-lib 的 JSONObject 基礎操作
     */
    public void showJSONObject()
    {
        // 創建JSONObject
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("uName", "lmx");
        jsonObject.put("cId", "100");
        System.out.println(jsonObject);
        // 輸出:{"uName":"lmx","cId":"100"}

        // 增加屬性
        jsonObject.element("pwd", "123456");
        System.out.println(jsonObject);
        // 輸出: {"uName":"lmx","cId":"100","pwd":"123456"}

        // 取值
        System.out.println("cId:" + jsonObject.get("cId"));
        // 輸出: cId:100

        // 判讀輸出對象的類型
        boolean isArray = jsonObject.isArray();
        boolean isEmpty = jsonObject.isEmpty();
        boolean isNullObject = jsonObject.isNullObject();

        System.out.println("是否數組:" + isArray);
        // 輸出: 是否數組:false
        System.out.println("是否空:" + isEmpty);
        // 輸出: 是否空:false
        System.out.println("是否空對象:" + isNullObject);
        // 輸出: 是否空對象:false

    }

    /**
     * 2. json-lib 的 JSONArray 添加到JSONObject 基礎操作
     */
    public void showJSONArrayAddJSONObject()
    {
        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        jsonArray.add(0, "lmx");
        jsonArray.add(1, "jqy");
        jsonObject.element("uName", jsonArray);
        System.out.println(jsonObject);
        // 輸出: {"uName":["lmx","jqy"]}

    }

    /**
     * 3. json-lib 的 JSONArray 基礎操作
     * 
     * @param jsonStr
     */
    public void showJSONArray()
    {

        // 創建JSONArray
        JSONArray jsonArray = new JSONArray();
        jsonArray.add(0, "lmx");
        jsonArray.add(1, "jqy");
        jsonArray.element("llh");

        System.out.println(jsonArray);
        // 輸出: ["lmx","jqy","llh"]

        // 根據下標返回,打印:2
        System.out.println(jsonArray.get(0));
        // 輸出: lmx

        // set修改
        jsonArray.set(0, "aa");
        System.out.println(jsonArray);
        // 輸出: ["aa","jqy","llh"]

        // 添加最前
        jsonArray.add(0, "bb");

        // 添加最後
        jsonArray.add("cc");
        System.out.println(jsonArray);
        // 輸出: ["bb","aa","jqy","llh","cc"]

        // jsonArray.clear(); 清空

    }

    /**
     * 4. json-lib 把JSONObject放入到JSONArray
     */
    public void showJSONObjectAddJSONArray()
    {

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("uName", "lmx");
        jsonObject.put("pwd", "123456");

        JSONObject jsonObject2 = new JSONObject();
        jsonObject2.put("uName", "lmx");
        jsonObject2.put("pwd", "123456");

        JSONArray jsonArray = new JSONArray();
        jsonArray.add(jsonObject);
        jsonArray.add(jsonObject2);
        System.out.println(jsonArray);
        // 輸出:[{"uName":"lmx","pwd":"123456"},{"uName":"lmx","pwd":"123456"}]

        for (int i = 0; i < jsonArray.size(); i++ )
        {
            System.out.println(jsonArray.get(i));
            // 輸出: 1. {"uName":"lmx","pwd":"123456"} 2. {"uName":"lmx","pwd":"123456"}
        }
    }

    /**
     * 5.json-lib 把 JavaBean轉換成json字符串
     */
    public void getJSONObjectToBean()
    {
        User user = new User();
        user.setcId("100");
        user.setuName("lmx");
        user.setPwd("123456");
        JSONObject jsonObject = JSONObject.fromObject(user);
        System.out.println(jsonObject);
        // 輸出: {"uName":"lmx","pwd":"123456","cId":"100"}
    }

    /**
     * 6.json-lib 把 json字符串轉換成JavaBean
     */
    public void getBeanToJSONObject()
    {
        String strJon = "{\"uName\":\"lmx\",\"pwd\":\"123456\",\"cId\":\"100\"}";
        JSONObject jsonObject = JSONObject.fromObject(strJon);
        User user = (User)JSONObject.toBean(jsonObject, User.class);
        System.out.println(user);
        // 輸出: {"uName":"lmx","pwd":"123456","cId":"100"}
    }

    /**
     * 7. json-lib 把 List轉換成json字符串
     */

    public void getListToJSONArray()
    {
        // List轉json字符串
        List<User> list = new ArrayList<User>();
        list.add(new User("100", "lmx", "123456"));
        list.add(new User("200", "jqy", "123"));
        JSONArray jsonArray = JSONArray.fromObject(list);
        System.out.println(jsonArray);
        // 輸出: [{"uName":"lmx","pwd":"123456","cId":"100"},{"uName":"jqy","pwd":"123","cId":"200"}]
    }

    /**
     * 8. json-lib 把 json字符串 轉換成 List
     */
    public void getJSONObjectToList()
    {
        List<User> userList = new ArrayList<User>();
        String strJon = "[{\"cId\":\"100\",\"uName\":\"lmx\",\"pwd\":\"123\"},{\"cId\":\"200\",\"uName\":\"jqy\",\"pwd\":\"123456\"}]";
        JSONArray jsonArray = JSONArray.fromObject(strJon);
        for (int i = 0; i < jsonArray.size(); i++ )
        {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            User user = (User)JSONObject.toBean(jsonObject, User.class);
            userList.add(user);
        }

        for (User user : userList)
        {
            System.out.println(user.getuName());
            // 輸出: lmx jqy
        }
    }

    /**
     * 9. json-lib 把 Map 轉換成 json字符串
     */
    public void getMapToJson()
    {
        Map<String, User> map = new HashMap<String, User>();
        map.put("1", new User("100", "lmx", "123456"));
        map.put("2", new User("200", "jqy", "123"));
        JSONObject jsonMap = JSONObject.fromObject(map);
        System.out.println(jsonMap);
        // 輸出:
        // {"1":{"uName":"lmx","pwd":"123456","cId":"100"},"2":{"uName":"jqy","pwd":"123","cId":"200"}}

    }

    /**
     * 10. json-lib 把 json字符串轉換成Map
     */
    public void getJsonToMap()
    {
        // json字符串轉Map
        String strJon = "{\"1\":{\"cId\":\"100\",\"uName\":\"lmx\"},\"2\":{\"cId\":\"200\",\"uName\":\"jqy\"}}";
        Map map = (Map)JSONObject.fromObject(strJon);
        Set set = map.keySet();
        Iterator ite = set.iterator();
        while (ite.hasNext())
        {
            String key = (String)ite.next();
            JSONObject jsonObject = JSONObject.fromObject(map.get(key));
            User user = (User)JSONObject.toBean(jsonObject, User.class);
            System.out.println(key + " " + JSONObject.fromObject(user).toString());
            // 輸出: 1 {"uName":"lmx","pwd":"","cId":"100"} 2{"uName":"jqy","pwd":"","cId":"200"}
        }
    }

    /**
     * 11. json-lib 把 JSONArray轉換成 List
     */
    public void getJSONArrayToList()
    {
        // List轉型JSONArray
        List<User> list = new ArrayList<User>();
        list.add(new User("100", "lmx", "123456"));
        list.add(new User("200", "jqy", "123"));
        JSONArray jsonArray = JSONArray.fromObject(list);
        System.out.println(jsonArray.toString());
        // 輸出:[{"uName":"lmx","pwd":"123456","cId":"100"},{"uName":"jqy","pwd":"123","cId":"200"}]

        // JSONArray轉型List
        List<User> lists = JSONArray.toList(jsonArray, new User(), new JsonConfig());
        Iterator<User> iur = lists.iterator();
        while (iur.hasNext())
        {
            User user = iur.next();
            System.out.println(JSONObject.fromObject(user).toString());
            // 輸出:{"uName":"lmx","pwd":"123456","cId":"100"}
            // {"uName":"jqy","pwd":"123","cId":"200"}
        }
    }

    /**
     * 12. json-lib 把JSONArray轉換成 數組
     */
    public void getJSONArrayToArray()
    {
        boolean[] boolArray = new boolean[] {true, false, true};
        JSONArray jsonArray = JSONArray.fromObject(boolArray);
        Object obj[] = jsonArray.toArray();
        for (Object o : obj)
        {
            System.out.println(o + " ");
            // 輸出: true false true
        }

    }

    /**
     * 13. json-lib 把數組轉換成 JSONArray
     */
    public void getArrayToJSONArray()
    {
        boolean[] boolArray = new boolean[] {true, false, true};
        JSONArray jsonArray = JSONArray.fromObject(boolArray);
        System.out.println(jsonArray.toString());
        // 輸出: [true,false,true]

    }

    /**
     * 14. json-lib 把XML轉換成 JSON
     */
    public void getXmlToJSON()
    {
        // XML轉JSON
        String xml = "<root>" + "<uName>lmx</uName>" + "<pwd>123456</pwd>" + "<birthday>"
                     + "<year>1990</year>" + "<month>10</month>" + "<day>22</day>" + "</birthday>"
                     + "</root>";
        XMLSerializer xmlSerializer = new XMLSerializer();
        JSON json = xmlSerializer.read(xml);
        System.out.println(json.toString());
        // 輸出:{"uName":"lmx","pwd":"123456","birthday":{"year":"1990","month":"10","day":"22"}}
    }
    
    /**
     * 14. json-lib 把JSON轉換成 XML
     */
    public void getJSONToXml()
    {
        String jsondata = "{\"uName\":\"lmx\",\"pwd\":\"123456\",\"birthday\":{\"year\":\"1990\",\"month\":\"10\",\"day\":\"22\"}}";  
    JSONObject jsonObject = JSONObject.fromObject(jsondata);  
    String xmlstr = new XMLSerializer().write(jsonObject);  
    System.out.println(xmlstr); 
    // 輸出: <?xml version="1.0" encoding="UTF-8"?><o><birthday class="object"><day type="string">22</day><month type="string">10</month><year type="string">1990</year></birthday><pwd type="string">123456</pwd><uName type="string">lmx</uName></o>
        
    }
    

    public static void main(String[] args)
    {
        // TODO Auto-generated method stub
        SfJson sf = new SfJson();

        // 1
        System.out.println("showJsonObject:");
        sf.showJSONObject();

        // 2
        System.out.println("showJSONArrayAddJSONObject:");
        sf.showJSONArrayAddJSONObject();

        // 3
        System.out.println("showJSONArray:");
        sf.showJSONArray();

        // 4
        System.out.println("showJSONObjectAddJSONArray:");
        sf.showJSONObjectAddJSONArray();

        // 5
        System.out.println("getJSONObjectToBean:");
        sf.getJSONObjectToBean();

        // 6
        System.out.println("getBeanToJSONObject:");
        sf.getJSONObjectToBean();

        // 7
        System.out.println("getListToJSONArray:");
        sf.getListToJSONArray();

        // 8
        System.out.println("getJSONObjectToList:");
        sf.getJSONObjectToList();

        // 9
        System.out.println("getMapToJson:");
        sf.getMapToJson();

        // 10
        System.out.println("getJsonToMap:");
        sf.getJsonToMap();

        // 11
        System.out.println("getJSONArrayToList:");
        sf.getJSONArrayToList();

        // 12
        System.out.println("getJSONArrayToArray:");
        sf.getJSONArrayToArray();

        // 13
        System.out.println("getArrayToJSONArray:");
        sf.getArrayToJSONArray();

        // 14
        System.out.println("getXmlToJSON:");
        sf.getXmlToJSON();
        
        // 15
        System.out.println("getJSONToXml:");
        sf.getJSONToXml();

    }

}


Json字符串轉對象和轉List集合操作(alibabab版本)

https://blog.csdn.net/liangmaoxuan/article/details/80640259


總結不好多多擔待,文章只單純個人總結,如不好勿噴,技術有限,有錯漏麻煩指正提出。本人QQ:373965070


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章