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)