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

示例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();

 

文章来自:https://www.cnblogs.com/lyon91/p/8417554.html
© 2021 jiaocheng.bubufx.com  联系我们
ICP备案:鲁ICP备09046678号-3