String转(alibaba fastJSON) JSONObject JSONArray javaBean

JSONObject继承JSON,JSONObject实现了Map, Cloneable, Serializable, InvocationHandler,JSONObject可以当做日常开发中的Map; 

 JSONArray继承JSON,JSONArray实现了List, Cloneable, RandomAccess, Serializable,JSONArray可以当做日常开发中的LIst;

JSONObject对象转换为String时可调用.toString()也可调用.toJSONString(),实际源码中.toString()调用的.toJSONString().

class Student{
    private String name;
    private Integer age;

    public void setName(String name){
        this.name = name;
    }

    public String getName(){
        return name;
    }

    public void setAge(Integer age){
        this.age = age;
    }

    public Integer getAge(){
        return age;
    }
}

public static void main(String[] args){

        //String --> JSONObject
        String str = "{\"age\":2, \"name\":\"zc\"}";
        JSONObject jsonObject = JSON.parseObject(str);
        System.out.println(jsonObject);
        String strCopy = jsonObject.toString(); //toString调用toJSONString
        System.out.println(strCopy);

        //Array --> JSONArray
        String str1 = "[{\"age\": 2, \"name\": \"czcz\"}, {\"addr\":\"bj\"}]";
        JSONArray array = JSON.parseArray(str1);
        for(Object a:array){
            JSONObject o = (JSONObject)a;
            System.out.println(o);
        }

        //String And Array --> JSONString And JSONArray
        String str2 = "{\"age\":[{\"age1\": 3}, {\"age2\": 4}, {\"age3\": 5}]}";
        JSONObject jsonObject1 = JSON.parseObject(str2);
        JSONArray array1 = JSON.parseArray(jsonObject1.getString("age"));
        System.out.println(array1);
        for(Object o:array1){
            JSONObject object = (JSONObject)o;
            System.out.println(object);
        }

        //JSON --> javaBean
        Student stu = JSON.parseObject(str, new TypeReference(){});
        System.out.println("age: " + stu.getAge() + " " + "name: " + stu.getName());
    }

 运行截图:

String转(alibaba fastJSON) JSONObject JSONArray javaBean_第1张图片

你可能感兴趣的:(后台开发实习学习笔记,fastJSON,alibaba)