Fastjson toJSONString、writeJSONString

toJSONString

  • Fastjson将Java对象序列化为JSON字符串,fastjson提供了一个最简单的入口
    package com.alibaba.fastjson;
    public abstract class JSON {
        public static String toJSONString(Object object);
    }
    
  • Sample
    import com.alibaba.fastjson.JSON;
    Model model = new Model();
    model.id = 1001;
    String json = JSON.toJSONString(model);
    

writeJSONString

  • Fastjson在1.2.11版本中,JSON类新增对OutputStream/Writer直接支持。
    package com.alibaba.fastjson;
    public abstract class JSON {
       public static final int writeJSONString(OutputStream os, // 
                                                 Object object, // 
                                                 SerializerFeature... features) throws IOException;
        public static final int writeJSONString(OutputStream os, //
                                                 Charset charset, //  
                                                 Object object, // 
                                                 SerializerFeature... features) throws IOException;
       public static final int writeJSONString(Writer os, // 
                                                 Object object, // 
                                                 SerializerFeature... features) throws IOException;
    }
    
  • Sample
    import com.alibaba.fastjson;
    import java.nio.charset.Charset;
    class Model {
    public int value;
    }
    Model model = new Model();
    model.value = 1001;
    OutputStream os = ...;
    JSON.writeJSONString(os, model);
    JSON.writeJSONString(os, Charset.from("GB18030"), model);
    Writer writer = ...;
    JSON.writeJSONString(os, model);
    
  • parseObject:在1.2.11版本中,fastjson新增加了对InputStream的支持支持。
    package com.alibaba.fastjson;
    public abstract class JSON {
        public static <T> T parseObject(InputStream is, //
                                        Type type, //
                                        Feature... features) throws IOException;
        public static <T> T parseObject(InputStream is, //
                                        Charset charset, //
                                        Type type, //
                                        Feature... features) throws IOException;
    }
    
  • Sample
    import com.alibaba.fastjson;
    import java.nio.charset.Charset;
    class Model {
        public int value;
    }
    InputStream is = ...
    Model model = JSON.parseObject(is, Model.class);
    Model model2 = JSON.parseObject(is, Charset.from("UTF-8"), Model.class);
    
下一节:Fastjson当需要处理超大JSON文本时,需要Stream API,在fastjson-1.1.32版本中开始提供Stream API。