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

8 篇文章 0 订阅
7 篇文章 0 订阅
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


  • 9
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值