格式轉(zhuǎn)換

Json字符串和json對象

Json兩種格式:JSON對象格式的字符串、JSON對象的數(shù)組

{"name":"JSON","address":"北京市西城區(qū)","age":25}//JSON的對象格式的字符串

[{"name":"JSON","address":"北京市西城區(qū)","age":25}]//JSON對象格式的數(shù)組

Json對象(typeOf -> Object)對象的值可以用對象.屬性進(jìn)行訪問

var person={"name":"shily","sex":"女","age":"23"}//json對象
console.log(person);
console.log(person.name); // shiny
console.log(typeof person); // Object

Json字符串 (typeOf -> String)單引號或者雙引號

var person='{"name":"shily","sex":"女","age":"23"}';//json字符串
console.log(person)
console.log(person.name) // 輸出 undefined
console.log(typeof person) // String

Json對象和Json字符串的轉(zhuǎn)換

Json對象 -> Json 字符串 JSON.stringify(obj)
Json字符串 -> Json對象 JSON.parse(str)

Java對象轉(zhuǎn)換成json對象

JSONObject 和 JSONArray

public static void convertObject() {
    Student stu=new Student();
    stu.setName("JSON");
    stu.setAge("23");
    stu.setAddress("北京市西城區(qū)");
    //1、使用JSONObject
    JSONObject json = JSONObject.fromObject(stu);
    //2、使用JSONArray
    JSONArray array=JSONArray.fromObject(stu);
    String strJson=json.toString();
    String strArray=array.toString();
    System.out.println("strJson:"+strJson);
    System.out.println("strArray:"+strArray);
}
strJson:{"address":"北京市西城區(qū)","age":"23","name":"JSON"}
strArray:[{"address":"北京市西城區(qū)","age":"23","name":"JSON"}]

JSON字符串 -> Java對象

public static void jsonStrToJava(){
    //定義兩種不同格式的字符串
    String objectStr="{\"name\":\"JSON\",\"age\":\"24\",\"address\":\"北京市西城區(qū)\"}";
    String arrayStr="[{\"name\":\"JSON\",\"age\":\"24\",\"address\":\"北京市西城區(qū)\"}]";
    //1、使用JSONObject
    JSONObject jsonObject=JSONObject.fromObject(objectStr);
    Student stu=(Student)JSONObject.toBean(jsonObject, Student.class);
    //2、使用JSONArray
    JSONArray jsonArray=JSONArray.fromObject(arrayStr);
    //獲得jsonArray的第一個(gè)元素
    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);
}
stu:Student [name=JSON, age=24, address=北京市西城區(qū)]
stu2:Student [name=JSON, age=24, address=北京市西城區(qū)]

Integer 和 int

Integer是int的包裝類,int是java的一種基本數(shù)據(jù)類型
Integer必須實(shí)例化以后才能使用,而int變量可以直接使用
Integer實(shí)際上是對象的引用,當(dāng)new一個(gè)integer的時(shí)候?qū)嶋H上生成一個(gè)指針指向此對象,而int是直接存儲數(shù)據(jù)值。
integer的默認(rèn)值是null 而int的默認(rèn)值是0

public long longValue() //返回封裝數(shù)據(jù)的long類型數(shù)值
public double doubleValue()
public int intValue()
public static int parseInt(String s)
public static Integer valueOf(String s) 

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容