用第三方工具类,将JavaBean、List、Map<String,Object>转成JSON文本

导入第三方jar包:

    》commons-beanutils-1.7.0.jar

    》commons-collections-3.1.jar

    》commons-lang-2.5.jar

    》commons-logging-1.1.1.jar

》ezmorph-1.0.3.jar

》json-lib-2.1-jdk15.jar            

   (1)JavaBean->JSON

             》JSONArray jsonArray = JSONArray.fromObject(city);

             》String jsonJAVA = jsonArray.toString();

   (2)List<JavaBean>->JSON

        》JSONArray jsonArray = JSONArray.fromObject(cityList);

             》String jsonJAVA = jsonArray.toString();

   (3)List<String>->JSON

        》JSONArray jsonArray = JSONArray.fromObject(stringList);

             》String jsonJAVA = jsonArray.toString();

(4)Map<String,Object>->JSON【重点】

package loaderman.bean2json;

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

import net.sf.json.JSONArray;

import org.junit.Test;

/**
 * 演示用第三方工具类,将JavaBean、List、Map<String,Object>转成JSON文本
 **/
public class TestJson {
    @Test
    public void javabean2json() {
        User user = new User(1, "哈哈", 123, "男");
        JSONArray jsonArray = JSONArray.fromObject(user);
        String jsonJAVA = jsonArray.toString();
        System.out.println(jsonJAVA);
        //[{"id":1,"name":"哈哈","sal":7000}]
    }

    @Test
    public void list2json() {
        List<User> userList = new ArrayList<User>();
        userList.add(new User(1, "恩和", 123, "男"));
        userList.add(new User(2, "恩和老婆", 123, "男"));
        userList.add(new User(3, "恩和小孩", 24, "男"));
        JSONArray jsonArray = JSONArray.fromObject(userList);
        String jsonJAVA = jsonArray.toString();
        System.out.println(jsonJAVA);
        //[{"id":1,"name":"恩和","sal":7000},{"id":2,"name":"福老婆","sal":8000},{"id":3,"name":"恩和","sal":20000}]
    }

    @Test
    public void map2json() {
        List<User> userList = new ArrayList<User>();
        userList.add(new User(1, "张三", 7000, "男"));
        userList.add(new User(2, "张三老婆", 8000, "女"));
        userList.add(new User(3, "张三小孩", 20000, "男"));
        userList.add(new User(4, "张三小孩的小孩", 40000, "男"));

        Map<String, Object> map = new HashMap<String, Object>();
        //total表示集合的长度
        map.put("total", userList.size());
        //rows表示集合内容
        map.put("rows", userList);

        JSONArray jsonArray = JSONArray.fromObject(map);
        String jsonJAVA = jsonArray.toString();
        System.out.println(jsonJAVA);

        jsonJAVA = jsonJAVA.substring(1, jsonJAVA.length() - 1);

        System.out.println(jsonJAVA);
    }
}

 

posted on 2018-12-03 17:42  LoaderMan  阅读(617)  评论(0编辑  收藏  举报

导航