alibaba fastjson使用

前端之家收集整理的这篇文章主要介绍了alibaba fastjson使用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

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

/**
 * Created by Administrator on 2016/3/3.
 */
public class TestJSON {
    public static void main(String[] args) {
        List<String> list=new ArrayList<String>();
        list.add("11");
        list.add("12");
        list.add("13");
        String listStr = JSON.toJSONString(list);//集合转为json字符串
        System.out.println(listStr);
        System.out.println(list.toString());
        JSONArray jsonArray = (JSONArray) JSON.parse(listStr);//json字符串转为JSONArray or JSONObject
        System.out.println(jsonArray);
        for (Object object : jsonArray) {
            System.out.println(object);
        }

        JSONArray jsonArray1 = JSON.parseArray(listStr);//字符串数组解析为JSONArray
        System.out.println(jsonArray1==jsonArray);

        Map<String,String> map=new HashMap<String,String>();
        map.put("id","1");
        map.put("name","jack");
        map.put("age","17");
        map.put("sex","male");
        String mapStr = JSON.toJSONString(map);//map转换为json字符串
        System.out.println(mapStr);
        System.out.println(map.toString());
        JSONObject jsonObject = JSON.parSEObject(mapStr);//
        System.out.println(jsonObject);
        System.out.println(jsonObject.getString("name"));
        System.out.println(jsonObject.get("name"));
        
        TestUser user=new TestUser();
        user.setAge("11");
        JSONObject jsonObject1 = (JSONObject) JSON.toJSON(user);//javabean转换为Object
        System.out.println(jsonObject1.get("age"));
        TestUser user1 = JSON.parSEObject(mapStr,TestUser.class);
        System.out.println(user1.getId());

        List<TestUser> testUserList=new ArrayList<TestUser>();
        TestUser testUser=null;
        for (int i=0;i<3;i++){
            testUser=new TestUser();
            testUser.setId(i);
            testUser.setAge((i+10)+"");
            testUser.setName("jack"+i);
            testUser.setSex("male");
            testUserList.add(testUser);
        }

        String testUserListStr = JSON.toJSONString(testUserList);
        System.out.println(testUserListStr);
        List<TestUser> testUserList1 = JSON.parseArray(testUserListStr,TestUser.class);//将字符串数组解析程指定类型的集合
        System.out.println(testUserList1.size());

        String str="{\"name\":\"jack\"}";
        JSONObject obj = JSON.parSEObject(str);
        System.out.println(obj.get("name"));

    }

}

原文链接:https://www.f2er.com/json/289454.html

猜你在找的Json相关文章