格式转换

Json字符串和json对象

Json两种格式:JSON对象格式的字符串、JSON对象的数组

{"name":"JSON","address":"北京市西城区","age":25}//JSON的对象格式的字符串

[{"name":"JSON","address":"北京市西城区","age":25}]//JSON对象格式的数组

Json对象(typeOf -> Object)对象的值可以用对象.属性进行访问

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字符串的转换

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

Java对象转换成json对象

JSONObject 和 JSONArray

public static void convertObject() {
    Student stu=new Student();
    stu.setName("JSON");
    stu.setAge("23");
    stu.setAddress("北京市西城区");
    //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":"北京市西城区","age":"23","name":"JSON"}
strArray:[{"address":"北京市西城区","age":"23","name":"JSON"}]

JSON字符串 -> Java对象

public static void jsonStrToJava(){
    //定义两种不同格式的字符串
    String objectStr="{\"name\":\"JSON\",\"age\":\"24\",\"address\":\"北京市西城区\"}";
    String arrayStr="[{\"name\":\"JSON\",\"age\":\"24\",\"address\":\"北京市西城区\"}]";
    //1、使用JSONObject
    JSONObject jsonObject=JSONObject.fromObject(objectStr);
    Student stu=(Student)JSONObject.toBean(jsonObject, Student.class);
    //2、使用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);
}
stu:Student [name=JSON, age=24, address=北京市西城区]
stu2:Student [name=JSON, age=24, address=北京市西城区]

Integer 和 int

Integer是int的包装类,int是java的一种基本数据类型
Integer必须实例化以后才能使用,而int变量可以直接使用
Integer实际上是对象的引用,当new一个integer的时候实际上生成一个指针指向此对象,而int是直接存储数据值。
integer的默认值是null 而int的默认值是0

public long longValue() //返回封装数据的long类型数值
public double doubleValue()
public int intValue()
public static int parseInt(String s)
public static Integer valueOf(String s) 

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容