FastJson JSON对象及JavaBean之间的相互转换

一、解析Json 将Json 转换成java bean

 

示例1:JSON格式字符串与javaBean之间的转换。

json字符串与javaBean之间的转换推荐使用 TypeReference<T> 这个类,使用泛型可以更加清晰

 /**
     * json字符串-简单对象与JavaBean_obj之间的转换
     */
    public static void testJSONStrToJavaBeanObj(){

        Student student = JSON.parseObject(JSON_OBJ_STR, new TypeReference<Student>() {});

        //Student student1 = JSONObject.parseObject(JSON_OBJ_STR, new TypeReference<Student>() {});
//因为JSONObject继承了JSON,所以这样也是可以的

    }

示例2.2-json字符串-数组类型与javaBean之间的转换

  public static void testJSONStrToJavaBeanList(){
        
        ArrayList<Student> students = JSON.parseObject(JSON_ARRAY_STR, new TypeReference<ArrayList<Student>>() {});


        ArrayList<Student> students1 = JSONArray.parseObject(JSON_ARRAY_STR, new TypeReference<ArrayList<Student>>() {});

//因为JSONArray继承了JSON,所以这样也是可以的 }

 

二、对象转Json

C2Result c1 = new  C2Result();
c1.setErrorCode("0");
c1.setErrorText("成功");
String result = JSONObject.toJSON(c1).toString();

 

  List 转 JSONArray []

 JSONArray.fromObject(vos).toString();

 

posted @ 2018-02-05 14:48  lyon♪♫  阅读(386)  评论(0编辑  收藏  举报