FastJSON 资料

FastJSON 学习资料(更新…)

文章目录

1.JSON

​ Fastjson是一个Java库,可用于将Java对象转换为其JSON表示形式。它也可以用于将JSON字符串转换为等效的Java对象。Fastjson可以与任意Java对象一起使用,包括您没有源代码的预先存在的对象。

他是使用Fastjson的主要类。您通常将这两个方法称为

{ #toJSONString(Object)}和{#parseObject(String,Class)}

*示例:

Dog model = new Dog(1,"大黄");
String json = JSON.toJSONString(model); // 将模型序列化为Json
 /*输出json==》{"id":1,"name":"大黄"}*/
Dog model2 = JSON.parseObject(json, Dog.class); // 将json反序列化为model2
/*输出model2==》Dog{id=1, name='大黄'}*/

1.1 TypeReference[类型参考]

​ 如果您要序列化/反序列化的对象是{code ParameterizedType[参数化类型]} (即,至少包含一个类型参数,并且可能是数组),则必须使用 { #toJSONString(Object)}或{ #parseObject(String,Type,Feature [])}方法。这是一个用于序列化和反序列化{@code ParameterizedType}的

*示例:

List<Dog> list = new ArrayList<>();
list.add(new Dog(1, "黄狗"));
list.add(new Dog(2, "哈巴狗"));
list.add(new Dog(3, "流浪狗"));
JSONObject jsonObj = new JSONObject();
jsonObj.put("狗的品种",list);
System.out.println(jsonObj);
/*输出jsonObj==》{"狗的品种":[{"id":1,"name":"黄狗"},{"id":2,"name":"哈巴狗"},{"id":3,"name":"流浪狗"}]}*/
List<Dog> list2 = jsonObj.getObject("狗的品种", new TypeReference<List<Dog>>() {});
System.out.println(list2);
/*输出jlist2==》[Dog{id=1, name='黄狗'}, Dog{id=2, name='哈巴狗'}, Dog{id=3,name='流浪狗'}]*/

1.2 JSON#parseObject()系列

1.2.1 (String text, Feature… features)

参数1:String text

参数2:Feature… features[特征]

返回值:JSONObject

说明:enum[枚举] Feature

AutoCloseSource 自动关闭源|AllowComment 允许评论 |AllowUnQuotedFieldNames 允许使用非引号引起来的字段名称 |AllowSingleQuotes 允许单引号|InternFieldNames 实习生字段名称 |AllowISO8601DateFormat 允许ISO 8601日期格式 ……等等

*示例:

String txt="{\"狗的品种\":[{\"id\":1,\"name\":\",黄狗\"},,,,,,,,{\"id\":2,\"name\":\"哈巴狗\"}]}";
JSONObject jsonObject = JSON.parseObject(txt, Feature.AllowArbitraryCommas );
System.out.println(jsonObject);
/*输出jsonObject==》{"狗的品种":[{"name":",黄狗","id":1},{"name":"哈巴狗","id":2}]}*/
1.2.2 (String text)

参数1:String text

返回值:JSONObject

*示例:

String txt="{\"狗的品种\":[{\"id\":1,\"name\":\"黄狗\"},{\"id\":2,\"name\":\"哈巴狗\"}]}";
JSONObject jsonObject = JSON.parseObject(txt);
/*输出jsonObject==》{"狗的品种":[{"name":"黄狗","id":1},{"name":"哈巴狗","id":2}]}*/
1.2.3 (String text, TypeReference type, Feature… features)

参数1:String text //json字串

参数2:TypeReference type //类型参考

参数3:Feature… features

返回值: T

*示例:

String jsonStr = "[{\"id\":001,\",,,,,,,,name\":\"小杨\"}]";
List<Map> list = JSON.parseObject(jsonStr, new TypeReference<List<Map>>() {}, Feature.AllowArbitraryCommas);
/*输出list==》[{id=1, ,,,,,,,,name=小杨}]*/
1.2.4 (String json, Class clazz, Feature… features)

参数1:String json

参数2:Class clazz

参数3:Feature… features

返回值: T

说明:此方法将指定的Json反序列化为指定类的对象。如果指定的类是泛型类型,则不适合使用*,因为Java的类型清除功能将使其不具有泛型类型信息。因此,如果所需类型是泛型类型,则不应使用此方法。请注意,如果指定对象的字段中的任何一个都是泛型的,则此方法很好用,只是对象本身不应该是*泛型类型。

*示例:

String str="{,,,,,,,,,,\"id\":1,\"name\":\"黄狗\"}";
Dog dog = JSON.parseObject(str, Dog.class, Feature.AllowArbitraryCommas);
/*输出dog==》Dog{id=1, name='黄狗'}*/
1.2.5 (String text, Class clazz, ParseProcess processor, Feature… features)

参数1:String text

参数2: Class clazz

参数3:ParseProcess processor//解析过程

参数4:Feature… features

返回值: T

说明: interface ParseProcess 空接口

*示例:无

1.2.6 (String json, Type type, Feature… features)

参数1:String json //要从中反序列化对象的字符串

参数2:Type type //src的特定通用类型

参数3: Feature… features

返回值: T //字符串中类型为T的对象

说明:方法将指定的Json反序列化为指定类型的对象。如果指定的对象是泛型类型,则此方法*很有用。

使用Type 从 com.alibaba.fastjson.TypeReference}类获得此类型。例如,要获取 Collection }的类型,

应使用:Type type = new TypeReference <Collection >(){}.getType();

*示例:

String str="{\"二狗\":{\"id\":2,\"name\":\"花猫狗\"}}";
Map<String, Dog> map2 = JSON.parseObject(str, new TypeReference<Map<String, Dog>>() {}.getType(), Feature.AllowArbitraryCommas);
Dog dog = map2.get("二狗");
System.out.println(map2);//{二狗=Dog{id=2, name='花猫狗'}}
System.out.println(dog);//Dog{id=2, name='花猫狗'}
1.2.7(String input, Type clazz, ParseProcess processor, Feature… features)

参数1:String input

参数2:Type clazz

参数3: ParseProcess processor

参数4:Feature… features

返回值: T

*示例: 无

1.2.8 (String input, Type clazz, int featureValues, Feature… features)

参数1:String input

参数2:Type clazz

参数3:int featureValues//特征值

参数4:Feature… features

返回值: T

*示例:无

1.2.9(String input, Type clazz, ParserConfig config, Feature… features)

参数1:String input

参数2:Type clazz

参数3: ParserConfig config //解析器配置

参数4:Feature… features

返回值: T

*示例:无

1.2.10(String input, Type clazz, ParserConfig config, int featureValues,Feature… features)

参数1:String input

参数2:Type clazz

参数3: ParserConfig config //解析器配置

参数4:int featureValues

参数5:Feature… features

返回值: T

*示例:无

1.2.11 (String input, Type clazz, ParserConfig config, ParseProcess processor,int featureValues, Feature… features)

参数1:String input

参数2:Type clazz

参数3:ParserConfig config

参数4:ParseProcess processor

参数5:int featureValues

参数6:Feature… features

返回值: T

*示例:无

1.2.12 (byte[] bytes, Type clazz, Feature… features)

参数1:byte[] bytes

参数2:Type clazz

参数3: Feature… features

返回值: T

说明:此方法使用需谨慎

*示例:

String str="{\"二狗\":{\"id\":2,\"name\":\"花猫狗\"}}";
Map<String, Dog> map2 = JSON.parseObject(str.getBytes(), new TypeReference<Map<String, Dog>>() {}.getType(), Feature.AllowArbitraryCommas);
Dog dog = map2.get("二狗");
System.out.println(map2);//{二狗=Dog{id=2, name='花猫狗'}}
System.out.println(dog);//Dog{id=2, name='花猫狗'}
String str="{\"二狗\":{\"id\":2,\"name\":\"花猫狗\"}}";  //map
Dog dog = JSON.parseObject(str.getBytes(), new TypeReference<Dog>(){}.getType(), Feature.AllowArbitraryCommas);
System.out.println(dog); //Dog{id=0, name='null'}
String str="{\"id\":2,\"name\":\"花猫狗\"}";  //对象
Dog dog = JSON.parseObject(str.getBytes(), new TypeReference<Dog>(){}.getType(), Feature.AllowArbitraryCommas);
System.out.println(dog); //Dog{id=2, name='花猫狗'}
1.2.13 (byte[] bytes, int offset, int len, Charset charset, Type clazz, Feature… features)

参数1:byte[] bytes

参数2:int offset

参数3: int len

参数4: Charset charset //字符集

参数5: Type clazz

参数6: Feature… features

返回值: T

*示例:无

1.2.14(byte[] bytes, Charset charset, Type clazz, ParserConfig config, ParseProcess processor, int featureValues, Feature… features)

参数1:byte[] bytes

参数2: Charset charset

参数2:int offset

参数3: ParserConfig config

参数4: ParseProcess processor

参数5: int featureValues

参数6: Feature… features

返回值: T

*示例:无

1.2.15 (byte[] bytes, int offset, int len, Charset charset, Type clazz, ParserConfig config, ParseProcess processor, int featureValues, Feature… features)

参数1:byte[] bytes

参数2:int offset

参数3:int len

参数4:Charset charset

参数2:ParserConfig config //解析过程

参数3: int featureValues //特征值

参数4: Feature… features

返回值: T

*示例:无

1.2.16 (byte[] input, int off, int len, CharsetDecoder charsetDecoder, Type clazz, Feature… features)

参数1:byte[] bytes

参数2:int off,

参数3: int len,

参数4: CharsetDecoder charsetDecoder,

参数5: Type clazz,

参数6: int len,

参数7:Feature… features

返回值: T

*示例:

1.2.17 (char[] input, int length, Type clazz, Feature… features)

参数1:char[] input

参数2:int length

参数3:Type clazz

参数4:Feature… features

返回值: T

*示例:

String str="{\"id\":2,\"name\":\"花猫狗\"}";
Dog dog= JSON.parseObject(str.toCharArray(), 
                   str.toCharArray().length,
      new TypeReference<Dog>() {}.getType(),
              Feature.AllowArbitraryCommas);
System.out.println(dog);//Dog{id=2, name='花猫狗'}
1.2.18(InputStream is, Type type, Feature… features)

参数1:InputStream is //输入流

参数2:Type type

参数3:Feature… features

返回值: T

说明:

需要定义 InputStream的子类的应用程序必须始终提供一种返回下一个输入字节的方法。

*示例:

 try {
   FileInputStream fis = new FileInputStream("C:\\Users\\admin\\Desktop\\demo.json");
  Dog dog = JSON.parseObject(fis, 
new TypeReference<Dog>() {}.getType(), 
new Feature[]{Feature.AllowArbitraryCommas});
System.out.println(dog);     //Dog{id=1, name='黄狗'}
      } catch (Exception e) {
        e.printStackTrace();
      }
1.2.19 (InputStream is, Charset charset, Type type, Feature… features)

参数1:InputStream is //输入流

参数2:Charset charset

参数3:Type type

参数4:Feature… features

返回值: T

*示例:无

    try {
FileInputStream fis = new FileInputStream("C:\\Users\\admin\\Desktop\\demo.json");
Dog dog = JSON.parseObject(fis, Charset.forName("UTF-8"), 
new TypeReference<Dog>() {}.getType(), 
new Feature[]{Feature.AllowArbitraryCommas});
System.out.println(dog);//Dog{id=1, name='黄狗'}
        } catch (Exception e) {
            e.printStackTrace();
        }
1.2.20 (InputStream is, Charset charset, Type type, ParserConfig config, Feature… features)

参数1:InputStream is

参数2:Charset charset

参数3:Type type

参数4: ParserConfig config

参数5: Feature… features

返回值: T

*示例:无

1.2.21 (InputStream is, Charset charset,Type type, ParserConfig config, ParseProcess processor, int featureValues,Feature… features)

参数1:InputStream is

参数2:Charset charset

参数3:Type type

参数4: ParserConfig config

参数5: ParseProcess processor

参数6: Feature… features

返回值: T

*示例:无

1.3 JSON#toJSON(Object)系列

1.3.1 (Object javaObject)

参数1: Object javaObject

返回值:Object

说明:此方法将指定的对象序列化为与之等效的表示形式;

*示例:

Object dog = JSON.toJSON(new Dog(2, "二狗"));
System.out.println(dog);  //{"name":"二狗","id":2}

//************************************************
Dog dog = (Dog) JSON.toJSON(new Dog(2, "二狗"));
System.out.println(dog);  
 //java.lang.ClassCastException: com.alibaba.fastjson.JSONObject cannot be cast to com.xxx.pojo.Dog  强转会报错
1.3.2 (Object javaObject, SerializeConfig config)

参数1:Object javaObject

参数2:SerializeConfig config //序列化配置

返回值:Object

说明:此方法强转具体类型会报错

*示例:

Object dog =JSON.toJSON(new Dog(2, "二狗"),
        SerializeConfig.globalInstance);
System.out.println(dog);  //{"name":"二狗","id":2}
//********************************************************************
Object dog =JSON.toJSON(new Dog(2, "二狗"),
        (ParserConfig) SerializeConfig.globalInstance
               .get( new TypeReference<Dog>() {}.getType()));
System.out.println(dog);  //{"name":"二狗","id":2}

1.4JSON#toJSON(Object)系列

1.4.1 (JSON json, Class clazz)

参数1:JSON json //等同于JsonObject类型

参数2: Class clazz

返回值: T

*示例:

JSONObject jsonObject = new JSONObject();
jsonObject.put("id",02);
jsonObject.put("name","二狗");
Dog dog = JSON.toJavaObject(jsonObject, Dog.class);
System.out.println(dog);  //Dog{id=2, name='二狗'}

@[top]

2.其他

@[top]
####2.1对象类型的之间的转换

1.1准备user对象

public class User {
    private int id;
    private String name;
    private int age;
    @Format(formats = {"yyyy-MM-yy hh:ss:mm"})
    private Date creatTime;
    private Dog dog2;
    private List<Dog> dog;
    //省略get set...
    }
public class Dog {
    private int id;
    private String name;
     //省略get set...
    }

1.2测试

    public void userMapper3(){
        ArrayList<Dog> list = new ArrayList<>();
        Dog dog = new Dog(1, "黄狗");
        Dog dog2 = new Dog(2, "二狗");
        Dog dog3 = new Dog(2, "花猫狗");
        list.add(dog);
        list.add(dog2);
        User user = new User(1,"张三",18,new Date());
        user.setDog(list);
        user.setDog2(dog3);
   //****************************************************     
         String s = JSON.toJSONString(user); //转化为String
         System.out.println(s); 
        User user1 = JSON.parseObject(s, User.class);//转化为对象
        System.out.println(user1);
        
        }
// System.out.println(s); 
{
  "age": 18,
  "creatTime": 1616714254785,
  "dog": [
    {
      "id": 1,
      "name": "黄狗"
    },
    {
      "id": 2,
      "name": "二狗"
    }
  ],
  "dog2": {
    "id": 2,
    "name": "花猫狗"
  },
  "id": 1,
  "name": "张三"
}

     String s = JSON.toJSONString(user); //转化为String
     System.out.println(s); 
    User user1 = JSON.parseObject(s, User.class);//转化为对象
    System.out.println(user1);
    
    }

```json
// System.out.println(s); 
{
  "age": 18,
  "creatTime": 1616714254785,
  "dog": [
    {
      "id": 1,
      "name": "黄狗"
    },
    {
      "id": 2,
      "name": "二狗"
    }
  ],
  "dog2": {
    "id": 2,
    "name": "花猫狗"
  },
  "id": 1,
  "name": "张三"
}

欢迎…大家批评指正…

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值