FastJson JSON源码学习

JSON类的JavaDoc

This is the main class for using Fastjson. You usually call these two methods toJSONString(Object) and parseObject(String, Class).
Here is an example of how fastjson is used for a simple Class:

Model model = new Model();
String json = JSON.toJSONString(model); // serializes model to Json
Model model2 = JSON.parseObject(json, Model.class); // deserializes json into model2

If the object that your are serializing/deserializing is a ParameterizedType
(i.e. contains at least one type parameter and may be an array) then you must use the
toJSONString(Object) or parseObject(String, Type, Feature[]) method. Here is an
example for serializing and deserialing a ParameterizedType:

String json = "[{},...]";
Type listType = new TypeReference<List<Model>>() {}.getType();
List<Model> modelList = JSON.parseObject(json, listType);

ParameterizedType

ParameterizedTypeType的子接口,表示一个有参数的类型,例如Collection<T>Map<K,V>等。但实现上 ParameterizedType并不直接表示Collection<T>Map<K,V>等,而是表示 Collection<String>Map<String,String>等这种具体的类型。是不是看着眼熟,其实这就是我们常说的泛型。而ParameterizedType代表的是一个泛型的实例,我们就称ParameterizedType为“泛型实例”吧。
当创建泛型P(如:Collection<String>)时,将解析P实例化的泛型类型声明(如:Collection<T>),并且递归地创建P的所有泛型参数(如:String)。
实现这个接口的“类”必须实现一个equals()方法,该方法将任何“泛型类型”(如:Collection<T>)声明相同且“类型参数”(如:String)也相同的两个“类”等同起来。

JSON属性

    public static TimeZone         defaultTimeZone      = TimeZone.getDefault();
    public static Locale           defaultLocale        = Locale.getDefault();
    public static String           DEFAULT_TYPE_KEY     = "@type";
    static final SerializeFilter[] emptyFilters         = new SerializeFilter[0];
    public static String           DEFFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
    public static int              DEFAULT_PARSER_FEATURE;
    public static int              DEFAULT_GENERATE_FEATURE;

    private static final ConcurrentHashMap<Type, Type> mixInsMapper = new ConcurrentHashMap<Type, Type>(16);
    
    static {
        int features = 0;
        features |= Feature.AutoCloseSource.getMask();
        features |= Feature.InternFieldNames.getMask();
        features |= Feature.UseBigDecimal.getMask();
        features |= Feature.AllowUnQuotedFieldNames.getMask();
        features |= Feature.AllowSingleQuotes.getMask();
        features |= Feature.AllowArbitraryCommas.getMask();
        features |= Feature.SortFeidFastMatch.getMask();
        features |= Feature.IgnoreNotMatch.getMask();
        DEFAULT_PARSER_FEATURE = features;
    }

    static {
        int features = 0;
        features |= SerializerFeature.QuoteFieldNames.getMask();
        features |= SerializerFeature.SkipTransientField.getMask();
        features |= SerializerFeature.WriteEnumUsingName.getMask();
        features |= SerializerFeature.SortField.getMask();
        DEFAULT_GENERATE_FEATURE = features;
        config(IOUtils.DEFAULT_PROPERTIES);
    }

配置方法

private static void config(Properties properties)
 public static void setDefaultTypeKey(String typeKey)

核心方法

parse()

public static Object parse(String text){}
public static Object parse(String text, int features){}
public static Object parse(String text, Feature... features){}
public static Object parse(String text, ParserConfig config){}
public static Object parse(String text, ParserConfig config, Feature... features){}
public static Object parse(String text, ParserConfig config, int features){}

public static Object parse(byte[] input, Feature... features){}
public static Object parse(byte[] input, int off, int len, CharsetDecoder charsetDecoder, int features) {}

parseObject()

public static JSONObject parseObject(String text)
public static <T> T parseObject(String text, Class<T> clazz)
public static JSONObject parseObject(String text, Feature... features)

 public static <T> T parseObject(String text, TypeReference<T> type, Feature... features) 
 public static <T> T parseObject(String json, Class<T> clazz, Feature... features)
 public static <T> T parseObject(String text, Class<T> clazz, ParseProcess processor, Feature... features)
 public static <T> T parseObject(String json, Type type, Feature... features)
 public static <T> T parseObject(String input, Type clazz, ParseProcess processor, Feature... features)
 public static <T> T parseObject(String input, Type clazz, int featureValues, Feature... features)
 public static <T> T parseObject(String input, Type clazz, ParserConfig config, Feature... features)
 public static <T> T parseObject(String input, Type clazz, ParserConfig config, int featureValues, Feature... features)
 public static <T> T parseObject(String input, Type clazz, ParserConfig config, ParseProcess processor, int featureValues, Feature... features)
 
 public static <T> T parseObject(byte[] bytes, Type clazz, Feature... features)
 public static <T> T parseObject(byte[] bytes, int offset, int len, Charset charset, Type clazz, Feature... features)
 public static <T> T parseObject(byte[] bytes, Charset charset, Type clazz, ParserConfig config, ParseProcess processor, int featureValues, Feature... features)
 public static <T> T parseObject(byte[] bytes, int offset, int len, Charset charset, Type clazz, ParserConfig config,   ParseProcess processor, int featureValues, Feature... features)
 public static <T> T parseObject(byte[] input,  int off, int len, CharsetDecoder charsetDecoder, Type clazz, Feature... features)
 
public static <T> T parseObject(char[] input, int length, Type clazz, Feature... features)
public static <T> T parseObject(InputStream is, Type type, Feature... features)
public static <T> T parseObject(InputStream is, Charset charset, Type type, ParserConfig config, ParseProcess processor, int featureValues, Feature... features)

parse()parseObject()方法大同小异,最终都是通过实例化一个DefaultJSONParser来进行解析处理,只是可能会对DefaultJSONParser设置不同的属性参数,然后通过DefaultJSONParser.parse()DefaultJSONParser.parseObject()方法来进行处理和操作。

DefaultJSONParser

构造函数,最终均使用该构造函数,仅在参数上有所区分

    public DefaultJSONParser(final Object input, final JSONLexer lexer, final ParserConfig config){
        this.lexer = lexer;
        this.input = input;
        this.config = config;
        this.symbolTable = config.symbolTable;

        int ch = lexer.getCurrent();
        if (ch == '{') {
            lexer.next();
            ((JSONLexerBase) lexer).token = JSONToken.LBRACE;
        } else if (ch == '[') {
            lexer.next();
            ((JSONLexerBase) lexer).token = JSONToken.LBRACKET;
        } else {
            lexer.nextToken(); // prime the pump
        }
    }

除此外,parseObject()方法还会设置其它参数

if (processor != null) {
    if (processor instanceof ExtraTypeProvider) {
        parser.getExtraTypeProviders().add((ExtraTypeProvider) processor);
    }

    if (processor instanceof ExtraProcessor) {
        parser.getExtraProcessors().add((ExtraProcessor) processor);
    }

    if (processor instanceof FieldTypeResolver) {
        parser.setFieldTypeResolver((FieldTypeResolver) processor);
    }
}

DefaultJSONParser.parse()

1、找到对应的ObjectDeserializer
2、序列化操作
2.1、找出Object对应的field及fieldClass(属性类型)
public static JavaBeanInfo build(Class<?> clazz //
            , Type type //
            , PropertyNamingStrategy propertyNamingStrategy //
            , boolean fieldBased //
            , boolean compatibleWithJavaBean
            , boolean jacksonCompatible
    )

public static Field getField(Class<?> clazz, String fieldName, Field[] declaredFields)
2.2、解析input,添加按规则添加至ResolveTask
3. 执行handleResovleTask()
4. 关闭parser,返回结果

DefaultJSONParser.parseObject(Type type, Object fieldName)

1、找到对应的ObjectDeserializer
2、反序列化操作
2.1、找出Object对应的field及fieldClass(属性类型)
2.2、解析input,添加按规则添加至ResolveTask
3. 执行handleResovleTask()
4. 关闭parser,返回结果
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
fastjson是一个开源的Java JSON库,可以用于处理JSON数据。操作JSON对象的常用方法如下: 1. 使用xxx.getJSONArray("key")方法可以获取JSON对象的JSON数组。 2. 使用xxx.getJSONObject(index)方法可以获取JSON数组的第index个JSON对象。 3. 使用xxx.getJSONObject("key")方法可以获取JSON对象内层名为"key"的内层JSON对象。 4. 使用xxx.getString("key")方法可以获取JSON对象中key为"key"的字符串值。 5. 使用12.toJSONString()或12.toString()方法可以将JSONObject对象转换为JSON字符串。 6. 使用7.getJSONObject(String key)方法可以根据key获取JSONObjct对象中对应的JSONObject对象。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [fastjsonjson对象的操作](https://blog.csdn.net/qq_45464560/article/details/119840692)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [FastJson中的JSONObject对象常用方法](https://blog.csdn.net/good_good_xiu/article/details/117744121)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值