FastJson的使用详解

使用只需导入:具体版本去阿里巴巴github官网

compile 'com.alibaba:fastjson:1.2.28'
compile 'com.alibaba:fastjson:1.1.56.android'


常用API:

Fastjson API入口类是com.alibaba.fastjson.JSON,常用的序列化操作都可以在JSON类上的静态方法直接完成。
//  public static final Object parse(String text); // 把JSON文本parse为JSONObject或者JSONArray

//  public static final JSONObject parseObject(String text); // 把JSON文本parse成JSONObject   

//  public static final <T> T parseObject(String text, Class<T> clazz); // 把JSON文本parse为JavaBean

//泛型也可以

T t =  com.alibaba.fastjson.JSON.parseObject(response.body().string(), new TypeReference<T>(){});

//  public static final JSONArray parseArray(String text); // 把JSON文本parse成JSONArray

//泛型也可以

 List<T> list =  com.alibaba.fastjson.JSON.parseObject(response.body().string(), new TypeReference<List<T>>(){});

//  public static final <T> List<T> parseArray(String text, Class<T> clazz); //把JSON文本parse成JavaBean集合

//  public static final String toJSONString(Object object); // 将JavaBean序列化为JSON文本

//  public static final String toJSONString(Object object, boolean prettyFormat); // 将JavaBean序列化为带格式的

JSON文本
//  public static final Object toJSON(Object javaObject);

将JavaBean转换为JSONObject或者JSONArray(和上面方法的区别是返回值是不一样的)


特殊用法日期格式化:

Date date=new Date();  
  //输出毫秒值   System.out.println(JSON.toJSONString(date));
  //默认格式为yyyy-MM-dd HH:mm:ss    System.out.println(JSON.toJSONString(date, SerializerFeature.WriteDateUseDateFormat));
  //根据自定义格式输出日期 System.out.println(JSON.toJSONStringWithDateFormat(date, "yyyy-MM-dd", SerializerFeature.WriteDateUseDateFormat));


序列化和反序列化:


  //将对象转换为JSON字符串

User user=new User();
  user.setName("Jack");
  user.setAge(24);
  String strJson=JSON.toJSONString(user);
  System.out.println("JSON="+strJson);


 //反序列化

String json="{\"name\":\"JACk\",\"age\":24}";
 User user=JSON.parseObject(json,User.class);
 System.out.println("name:"+user.getName()+", age:"+user.getAge());


//泛型的反序列化
  String json="{\"user\":{\"name\":\"Mack\",\"age\":24}}";
  Map<String, User> map = JSON.parseObject(json, new TypeReference<Map<String, User>>(){});

  Map<T, E> map = JSON.parseObject(json, new TypeReference<Map<T, E>>(){}); 

List<T> list = com.alibaba.fastjson.JSON.parseObject(response.body().string(), new TypeReference<List<T>>(){});

System.out.println(map.get("user"));



public <T> void getList(final OkBaseRequest req, final HttpCallback<List<T>> callback) {
    StringBuilder urlBuilder = new StringBuilder(req.baseUrl);
    if (req.jsonPareams == null && req.mapPareams != null && !req.mapPareams.isEmpty()) {
        urlBuilder.append("?");
        for (Map.Entry<String, String> entry : req.mapPareams.entrySet()) {
            urlBuilder.append(entry.getKey()).append("=").append(entry.getValue());
        }
    } else if (req.jsonPareams.length() > 0) {
        try {
            JSONObject object = new JSONObject(req.jsonPareams);
            Iterator<String> keys = object.keys();
            while (keys.hasNext()) {
                String key = keys.next();
                urlBuilder.append(key).append("=").append(object.get(key));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    Request request = new Request.Builder().url(urlBuilder.toString()).build();

    onStart(callback);
    Call call = client.newCall(request);
    addCallMaps(req.getRequestTag(), call);
    call.enqueue(new Callback() {

        @Override
        public void onFailure(Call call, IOException arg1) {
            onError(callback, arg1.getMessage());
            arg1.printStackTrace();
            removeCallMap(req.getRequestTag());
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            removeCallMap(req.getRequestTag());
            final List<T> list =  com.alibaba.fastjson.JSON.parseObject(response.body().string(), new TypeReference<List<T>>(){});
            //如果愿意也可以根据class如下
            //final List<T> list = (List<T>) com.alibaba.fastjson.JSON.parseArray(response.body().string(), req.reponseCls);
            if (response.isSuccessful() && list != null && list.size() > 0) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (callback != null)
                            callback.onSuccess(list);
                    }
                });
            } else {
                onError(callback, response.message());
            }
        }

    });

}

阅读更多
换一批

没有更多推荐了,返回首页