fastjson 阿里巴巴json使用

前端之家收集整理的这篇文章主要介绍了fastjson 阿里巴巴json使用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
引入jar包 fastjson-1.2.35.jar
<dependency>
 <groupId>com.alibaba</groupId>
 <artifactId>fastjson</artifactId>
 <version>1.2.35</version>
</dependency>

代码有注释,详细使用看代码,package com.haixing.testFastJson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

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

/**
 * Created by xuhaixing on 17-8-15.
 */
public class TestFastJson {
    public static void main(String[] args) {
        Student stu = new Student();
        stu.setStuId("001");
        stu.setStuName("小花");
        stu.setPassword("001");
        stu.setBirthday(new Date());

        HashMap<String,Object> map = new HashMap<>();
        map.put("1",stu);
        map.put("2",stu);

        List<Student> list = new ArrayList<Student>();
        list.add(stu);
        list.add(stu);

        String json1 = JSON.toJSONString(stu);
        System.out.println(json1);
        //{"age":0,"birthday":1502808058978,"password":"001","stuId":"001","stuName":"小花"}



        String json11 = JSON.toJSONString(stu,true); //带格式
        System.out.println(json11);
        /*{
        "age":0,                "birthday":1502808312496,                "password":"001",                "stuId":"001",                "stuName":"小花"
         }*/

        String json2 = JSON.toJSONStringWithDateFormat(stu,"yyyy-MM-dd hh-mm-ss"); //带日期格式
        System.out.println(json2);
        //{"age":0,"birthday":"2017-08-16 06-44-14","stuName":"小花"}


        Object json3 = JSON.toJSON(map);//转换为jsonObjectjsonArray类型
        System.out.println(json3);
        //{"1":{"birthday":1502837054708,"stuName":"小花","age":0},"2":{"birthday":1502837054708,"age":0}}

        json3 = JSON.toJSON(list);
        System.out.println(json3);
        //[{"birthday":1502837237363,{"birthday":1502837237363,"age":0}]


        String json = "{\"age\":0,\"password\":\"001\",\"stuId\":\"001\",\"stuName\":\"小花\"}";
        Object obj = JSON.parse(json);
        System.out.println(obj);

        JSONObject obj2 = JSON.parSEObject(json);//json文本转换为jsonObject
        System.out.println(obj2);

        JSONArray obj3 = JSON.parseArray(json3.toString());//json文本转换为jsonArray
        System.out.println(obj3);

        Student stu1 = JSON.parSEObject(json,Student.class); //json转换为对象
        System.out.println(stu1);

        List<Student> listStu = JSON.parseArray(json3.toString(),Student.class); //转换为对象集合
        System.out.println(listStu);

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

猜你在找的Json相关文章