fastjson的一些基本用法

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializerFeature;
import sun.nio.cs.US_ASCII;

import java.util.ArrayList;
import java.util.List;

/**
 * 演示FastJson的使用  序列化与反序列化
 */

/***
 * 综上所述:
 * fastJson对于json格式字符串的解析主要用到了一下三个类:
 * JSON:fastJson的解析器,用于JSON格式字符串与JSON对象及javaBean之间的转换。
 * JSONObject:fastJson提供的json对象。  可以将JSONObject当做一个MAP集合
 * JSONArray:fastJson提供json数组对象。  可以将JSONArray当做一个List集合 ,每一个List中的元素都放的是一个JSONObject
 *
 *
 *
 */

public class Main {

    public static void main(String[] args) {
        objToJsonString();
        jsonStringToObj1();
        jsonStringToObj2();
        jsonStringToJsonObj();
        jsonStringToJsonObj2();
        objToJSONObj();
        parseJSONAndBean();
      //  test2();
        arrayopt();
        parseJSONStrByTypeReference();
    }

    //======================================================================
    /**
     * java对象转换成jsonstring字符串(序列化成jsonString)
     */

    public static void objToJsonString(){
        Score score =new Score(12.3,14.3);
        User  user =new User("zhangsan","123456",score);
        String s = JSON.toJSONString(user);
        System.out.println(s);//{"password":"123456","score":{"shuxue":14.3,"yuwen":12.3},"userName":"zhangsan"}
    }
    /**
     * jsonString转换成obj(反序列化成javaben)
     */

    public static void jsonStringToObj1(){
        String s = "{\"password\":\"123456\",\"score\":{\"shuxue\":14.3,\"yuwen\":12.3},\"userName\":\"zhangsan\"}";
        User user = JSON.parseObject(s, User.class);
        //User{userName='zhangsan', password='123456', score=Score{yuwen=12.3, shuxue=14.3}}
        System.out.println(user);
    }
    /**
     * jsonString转换成obj(反序列化成javaben)
     */

    public static void jsonStringToObj2(){
        String s = "{\"password\":\"123456\",\"score\":{\"shuxue\":14.3,\"yuwen\":12.3},\"userName\":\"zhangsan\"}";
        User user = JSONObject.parseObject(s, User.class);
        //User{userName='zhangsan', password='123456', score=Score{yuwen=12.3, shuxue=14.3}}
        System.out.println(user);
    }

    /**
     * 反序列化成JSON对象
     * 注:JSONObject类是JSON类的子类
     */

    public static void jsonStringToJsonObj(){
        String s = "{\"password\":\"123456\",\"score\":{\"shuxue\":14.3,\"yuwen\":12.3},\"userName\":\"zhangsan\"}";
        JSONObject jsonObject = JSONObject.parseObject(s);
        System.out.println(jsonObject);
    }
    /**
     * 反序列化成JSON对象
     */

    public static void jsonStringToJsonObj2(){
        String s = "{\"password\":\"123456\",\"score\":{\"shuxue\":14.3,\"yuwen\":12.3},\"userName\":\"zhangsan\"}";
        JSONObject jsonObject = JSON.parseObject(s);
        System.out.println(jsonObject);
    }
    /**
     *
     *
     * java对象装换成json对象
     */

    public static  void objToJSONObj(){
        Score score =new Score(12.3,14.3);
        User  user =new User("zhangsan","123456",score);
        JSONObject jsonObject = (JSONObject)JSON.toJSON(user);
        System.out.println(jsonObject);
    }


    /**
     *
     * 直接将java对象序列化为json文本.,可以按照原有的类型反序列回来
     */

    public static  void parseJSONAndBean()
    {

      /*
        这样子会报转换异常
        //Exception in thread "main" java.lang.ClassCastException: com.alibaba.fastjson.JSONObject cannot be cast to User
        String s = "{\"password\":\"123456\",\"score\":{\"shuxue\":14.3,\"yuwen\":12.3},\"userName\":\"zhangsan\"}";
        User userObj = (User) JSON.parse(s);
        System.out.println(userObj);*/

        Score score =new Score(12.3,14.3);
        User  user =new User("zhangsan","123456",score);
        SerializerFeature[] featureArr = { SerializerFeature.WriteClassName };
        String text = JSON.toJSONString(user, featureArr);
        System.out.println(text);
        // 输出结果:{"@type":"User","password":"123456","score":{"shuxue":14.3D,"yuwen":12.3D},"userName":"zhangsan"}
        User userObj = (User) JSON.parse(text);
        System.out.println(userObj);
        // User{userName='zhangsan', password='123456', score=Score{yuwen=12.3, shuxue=14.3}}
    }

    /***
     * 这个方法会报错
     */

    public static  void test2()
    {

        Score score =new Score(12.3,14.3);
        User  user =new User("zhangsan","123456",score);

        String text = JSON.toJSONString(user);
        System.out.println("test="+text);
        // test={"password":"123456","score":{"shuxue":14.3,"yuwen":12.3},"userName":"zhangsan"}
        User userObj = (User) JSON.parse(text);
        System.out.println(userObj);
        // Exception in thread "main" java.lang.ClassCastException: com.alibaba.fastjson.JSONObject cannot be cast to User
    }
    //===
    /**
     *  json字符串与javaBean之间的转换推荐使用 TypeReference<T> 这个类
     */

    public static  void parseJSONStrByTypeReference(){
        Score score =new Score(12.3,14.3);
        User  user =new User("zhangsan","123456",score);
        String text = JSON.toJSONString(user);

        User user1 =JSON.parseObject(text,new TypeReference<User>(){});
        System.out.println(user1);

    }


    //========================对集合和数组的操作=============================================================
    /**
     *
     * json字符串数组转换为JSONArray
     *
     */

    public static  void arrayopt() {
        //方式1
        String  str ="[{\"password\":\"123456\",\"score\":{\"shuxue\":14.3,\"yuwen\":12.3},\"userName\":\"zhangsan\"},{\"password\":\"1234567890\",\"score\":{\"shuxue\":223.3,\"yuwen\":122.3},\"userName\":\"lisi\"}]";
        List<User> list = (List<User>) JSON.parse(str);
        System.out.println(list);

        //方式2
        JSONArray jsonArray = JSONArray.parseArray(str);
        for (Object obj:jsonArray) {
            JSONObject jsonObject =(JSONObject) obj;
            String userName = jsonObject.getString("userName");
            System.out.println(userName);
        }
        JSONObject jsonObject = jsonArray.getJSONObject(1);
        System.out.println(jsonObject);
    }

    public  static  void  arrayopt2() {
        //json数组
        String  str ="[{\"password\":\"123456\",\"score\":{\"shuxue\":14.3,\"yuwen\":12.3},\"userName\":\"zhangsan\"},{\"password\":\"1234567890\",\"score\":{\"shuxue\":223.3,\"yuwen\":122.3},\"userName\":\"lisi\"}]";
        List<User> list = JSON.parseObject(str,new TypeReference<ArrayList<User>>(){});


    }


}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值