您的位置:首页 > Web前端 > JavaScript

fastJson解析框架的学习

2014-12-08 20:27 351 查看
最近偶然间看到了以前写过的代码,发现了以前用的非常频繁的json解析框架fastjson。这个框架的确非常方便,帮助开发者省了很多的人工代码。以前那是因为没有时间写学习其中的原理,周末抽了点时间分析了下他的源码,可以作为不错的json解析框架的资料。主要分为2个步骤,1个是对象转json字符串,还有1个是json字符转对象的处理。

fastjson介绍

fastjson是阿里巴巴内部的json解析框架,目前代码已经开源在alibaba的github上了,等会想要研究的fastjson的同学可以上github进行源码下载。链接为https://github.com/alibaba/fastjson.git,上面一堆的开源项目,一找就找到了。fastjson是用java语言写的,可以放在eclipse上进行源码的阅读。

搭建fastjson源码阅读环境

这个必须得说一下,这个可不是根据源码文件,逐个文件在代码编辑器中打开再阅读,这样效率太低,下面介绍一下步骤:

1.到github上下载源码,这个很简单,谁都会。

2.将里面的com核心的代码目录解压出来,因为你下载的压缩包很多东西不是你所需要的。



3.将下载好的fastjson代码在eclipse上进行代码关联,如果在没有任何操作之前,阅读代码会出现下面的状况:



关联步骤为:



4.执行完上述操作后,就可以查看源码像查找自己本地的代码一样了。

测试的环境

在运行fastjson的2个功能前,我写了个测试场景类和对象类,首先声明类A:

public class A {
	private int age;
	private String name;
	
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	public void showInfo(){
		System.out.println(this.name + ":" + this.age);
	}
}


然后是场景测试类的代码:

/**
 * fastjson测试场景类
 * @author lyq
 *
 */
public class Client {
	public static void main(String[] args){
		String str;
		A a = null;
		A a2 = new A();
		
	//	B b = null;
	//	B b2 = new B();
		
		a2.setAge(11);
		a2.setName("zs");
		str = JSON.toJSONString(a2);
		
		System.out.println(str);
		a = JSON.parseObject(str, A.class);
		
		a.showInfo();
	}
}
测试程序不需要这么复杂,简简单单就好。下面是运行结果:

{"age":11,"name":"zs"}
zs:11
正如想象中一样,非常正确。

对象转json字符

下面看看第一个过程的分析,就是对象转字符的过程。我们可以开始看代码:

a2.setAge(11);
		a2.setName("zs");
		str = JSON.toJSONString(a2);
		
		System.out.println(str);
		a = JSON.parseObject(str, A.class);
到了第3行往里点:

public static final String toJSONString(Object object) {
        return toJSONString(object, new SerializerFeature[0]);
    }

    public static final String toJSONString(Object object, SerializerFeature... features) {
        SerializeWriter out = new SerializeWriter();

        try {
            JSONSerializer serializer = new JSONSerializer(out);
            for (com.alibaba.fastjson.serializer.SerializerFeature feature : features) {
                serializer.config(feature, true);
            }

            serializer.write(object);

            return out.toString();
        } finally {
            out.close();
        }
    }
就会连续经过这2个方法,这里就蹦出了几个新的类定义,反正最后就是通过返回out.toString()的形式就是最终的json字符串了。out在这里是一个写入器,这个写入器在JSONSerializer包构造,然后调用write写入Object对象。下面是关键的write方法:

public final void write(Object object) {
        if (object == null) {
            out.writeNull();
            return;
        }

        Class<?> clazz = object.getClass();
        ObjectSerializer writer = getObjectWriter(clazz);

        try {
            writer.write(this, object, null, null, 0);
        } catch (IOException e) {
            throw new JSONException(e.getMessage(), e);
        }
    }
获取ObjectSerializer写入类型,往里面写东西,这里的ObjectSerializer只是个接口:

public interface ObjectSerializer {

    void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException;
}
真正的操作在他的子类上,他的子类有如下:



基本涵盖了所有的基本数据类型,我们抽出一个子类看看他是怎么写入的:

public class BooleanArraySerializer implements ObjectSerializer {

    public static BooleanArraySerializer instance = new BooleanArraySerializer();

    public final void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
        SerializeWriter out = serializer.getWriter();
        
        if (object == null) {
            if (out.isEnabled(SerializerFeature.WriteNullListAsEmpty)) {
                out.write("[]");
            } else {
                out.writeNull();
            }
            return;
        }
        
        boolean[] array = (boolean[]) object;
        out.write('[');
        for (int i = 0; i < array.length; ++i) {
            if (i != 0) {
                out.write(',');
            }
            out.write(array[i]);
        }
        out.write(']');
    }
}
首先获取写入的目标对象,就是刚刚的out,写入流程很好理解,因为是数组,先下[,中间写具体的对象数据,在补上]补齐。其他的数据类型写入方式原理也大体一致。于是一个大体的类关系图就出来了:



这里作者比较好的设计是针对不同的类型定义不同的数据类型写入器,但是调用的时候用了统一的调用形式。

json字符串转化为对象

这个过程从字面理解也知道一定比上面的操作难。这里面也涉及了很多层的调用,再次回到刚刚的场景类代码:

a2.setAge(11);
		a2.setName("zs");
		str = JSON.toJSONString(a2);
		
		System.out.println(str);
		a = JSON.parseObject(str, A.class);
到了最后一步代码的时候,停下,由于过程复杂,这里我设置了断点的调试方法,下面是我截的图片:











关键来到了看一下这个方法,名为

@SuppressWarnings({ "unchecked", "rawtypes" })
    public final Object parseObject(final Map object, Object fieldName) {
        final JSONLexer lexer = this.lexer;
里面声明了一个lexer变量,他也是一个接口,下面有2个实现的子类:



这个类就是一个扫描器性质的类,里面维护了一个text的json字符串对象,然后这个类就在里面逐个扫描,取出对应的键值对,放入对象中。

public final class JSONScanner extends JSONLexerBase {

    private final String text;

    public JSONScanner(String input){
        this(input, JSON.DEFAULT_PARSER_FEATURE);
    }

    public JSONScanner(String input, int features){
        this.features = features;

        text = input;
        bp = -1;

        next();
        if (ch == 65279) {
            next();
        }
    }
Input输入值作为text内部对象进行扫描,bp为扫描的下标。解析操作的核心就是通过这个扫描类实现的,主要步骤为3步

1.取出key

2.得到class类型

3.取出value

4.Object设置key,value。

第一步:

boolean isObjectKey = false;
                Object key;
                if (ch == '"') {
                    key = lexer.scanSymbol(symbolTable, '"');
                    lexer.skipWhitespace();
                    ch = lexer.getCurrent();
                    if (ch != ':') {
                        throw new JSONException("expect ':' at " + lexer.pos() + ", name " + key);
                    }
                } else if (ch == '}') {
                    lexer.next();
                    lexer.resetStringPosition();
                    lexer.nextToken();
                    return object;
                } else if (ch == '\'') {
                    if (!isEnabled(Feature.AllowSingleQuotes)) {
                        throw new JSONException("syntax error");
                    }

                    key = lexer.scanSymbol(symbolTable, '\'');
                    lexer.skipWhitespace();
                    ch = lexer.getCurrent();
第二步获取相关类实例,这里必然用了反射的思想;

if (key == JSON.DEFAULT_TYPE_KEY) {
                    String typeName = lexer.scanSymbol(symbolTable, '"');
                    Class<?> clazz = TypeUtils.loadClass(typeName);

                    if (clazz == null) {
                        object.put(JSON.DEFAULT_TYPE_KEY, typeName);
                        continue;
                    }

                    lexer.nextToken(JSONToken.COMMA);
                    if (lexer.token() == JSONToken.RBRACE) {
                        lexer.nextToken(JSONToken.COMMA);
                        try {
                            Object instance = null;
                            ObjectDeserializer deserializer = this.config.getDeserializer(clazz);
                            if (deserializer instanceof ASMJavaBeanDeserializer) {
                                instance = ((ASMJavaBeanDeserializer) deserializer).createInstance(this, clazz);
                            } else if (deserializer instanceof JavaBeanDeserializer) {
                                instance = ((JavaBeanDeserializer) deserializer).createInstance(this, clazz);
                            }

                            if (instance == null) {
                                if (clazz == Cloneable.class) {
                                    instance = new HashMap();
                                } else {
                                    instance = clazz.newInstance();
                                }
                            }

                            return instance;
                        } catch (Exception e) {
                            throw new JSONException("create instance error", e);
                        }
                    }
3,4步的操作:

Object value;
                if (ch == '"') {
                    lexer.scanString();
                    String strValue = lexer.stringVal();
                    value = strValue;

                    if (lexer.isEnabled(Feature.AllowISO8601DateFormat)) {
                        JSONScanner iso8601Lexer = new JSONScanner(strValue);
                        if (iso8601Lexer.scanISO8601DateIfMatch()) {
                            value = iso8601Lexer.getCalendar().getTime();
                        }
                        iso8601Lexer.close();
                    }

                    object.put(key, value);
固定模式为,先scan扫描值,在取出后面紧挨着的值。JSON解析json字符类图:



然后到了操作的最后几步,断点调试如下:





以上就是对于fastjson的简单分析,做任何事都要抱着好奇的心态,这样就会有更多的收获的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: