JSON字符串轉爲JSON對象

在數據傳輸流程中,json是以文本,即字符串的形式傳遞的,而JS操做的是對象,因此,JSON對象(js對象)和JSON字符串之間的相互轉換是關鍵。html

JSON能夠有兩種格式,一種是對象格式的,另外一種是數組對象。java

//數據準備
var jsonStr = '{"name":"dxm", "password":"1111"}';

var jsonObj = {"name":"dxm", "password":"1111"};

一、json字符串與js對象轉換json

var jsonObj = $.parseJSON( jsonstr ); //jQuery提供,能夠將json字符串轉換成json對象
var str = jsonObj.toJSONString();
var jsonObj = eval('(' + jsonStr + ')'); //不推薦這些方式,這種方式不安全eval會執行json串中的表達式
var jsonObj = JSON.parse(jsonStr); //JSON.parse(string)將字符串轉爲JSON格式;
var jsonObj = JSON.stringify(jsonStr);//JSON.stringify(obj)將JSON轉爲字符串

二、JSON 字符串 與 java 對象的轉換數組

轉JSON字符串安全

//使用JSONObject
JSONObject json = JSONObject.fromObject(stu);
//使用JSONArray
JSONArray array=JSONArray.fromObject(stu);

轉java對象spa

public static void jsonStrToJava(){
        //定義兩種不一樣格式的字符串
        String objectStr="{\"name\":\"JSON\",\"age\":\"24\",\"address\":\"HZ\"}";
        String arrayStr="[{\"name\":\"JSON\",\"age\":\"24\",\"address\":\"HZ\"}]";
    
        //一、使用JSONObject
        JSONObject jsonObject=JSONObject.fromObject(objectStr);
        Student stu=(Student)JSONObject.toBean(jsonObject, Student.class);
        
        //二、使用JSONArray
        JSONArray jsonArray=JSONArray.fromObject(arrayStr);
        //得到jsonArray的第一個元素
        Object o=jsonArray.get(0);
        JSONObject jsonObject2=JSONObject.fromObject(o);
        Student stu2=(Student)JSONObject.toBean(jsonObject2, Student.class);
        System.out.println("stu:"+stu);
        System.out.println("stu2:"+stu2);
}

三、JSON 字符串 與集合的轉換code

list:htm

public static void listToJSON(){
        Student stu=new Student();
        stu.setName("JSON");
        stu.setAge("23");
        stu.setAddress("HZ");
        List<Student> lists=new ArrayList<Student>();
        lists.add(stu);
        //一、使用JSONObject
        //JSONObject listObject=JSONObject.fromObject(lists).toString();
        //二、使用JSONArray
        JSONArray listArray=JSONArray.fromObject(lists).toString();
        
    }
public static void jsonToList(){
        String arrayStr="[{\"name\":\"JSON\",\"age\":\"24\",\"address\":\"HZ\"}]";
          //轉化爲list
           List<Student> list2=(List<Student>)JSONArray.toList(JSONArray.fromObject(arrayStr), Student.class);//轉化爲數組
           Student[] ss =(Student[])JSONArray.toArray(JSONArray.fromObject(arrayStr),Student.class);
    }

Map:對象

public static void mapToJSON(){
        Student stu=new Student();
        stu.setName("JSON");
        stu.setAge("23");
        stu.setAddress("HZ");
        Map<String,Student> map=new HashMap<String,Student>();
        map.put("first", stu);
        
        //一、JSONObject
        JSONObject mapObject=JSONObject.fromObject(map).toString();//二、JSONArray
        JSONArray mapArray=JSONArray.fromObject(map).toString;
    }

 

 

 

 

參考:https://www.cnblogs.com/zq-boke/p/5833387.htmlblog

   https://www.cnblogs.com/teach/p/5791029.html

相關文章
相關標籤/搜索