一、Json的语法规则
数据在名称/值中
数据由逗号分隔
大括号保存对象
中括号保存数组
名称/值对包括字段名称(在双引号中),后面写一个冒号,然后是值
二、Json对象
Json对象在大括号{}中书写,例:
{"name":"硕硕","age":"16"}
三、Json数组
Json数组在中括号中书写:
{"Person":[
{"name":"硕硕","age":"16"},
{"name":"二硕","sex":"女"},
{"name":"二硕","sex":"女"}
]}
在上面的例子中,对象Person是包含三个对象的数组。
四、Json.parse()
使用Json.parse()方法将数据转换为JavaScript对象。
五、Json.stringify()
使用Json.stringify()方法将JavaScript对象转为字符串
六、手动拼接Json串
String a="{"+"\""+"email"+"\""+":"+"\""+email+"\""+","
+ ""+"\""+"nick_name"+"\""+":"+"\""+name+"\""+"}";
打印结果为:
{"email":"1","nick_name":"ze"}
七、将java对象转成Json对象
一个Customer对象和Result对象
public class Customer {
private String nick_name;
private String email;
public String getNick_name() {
return nick_name;
}
public void setNick_name(String nick_name) {
this.nick_name = nick_name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "Customer [nick_name=" + nick_name + ", email=" + email + ", getEmail()=" + getEmail() + ","
+ " getNick_name()=" + getNick_name() + ", getClass()=" + getClass() + ", hashCode()=" +
hashCode() + ", toString()=" + super.toString() + "]";
}
public class Result {
private Customer customer;
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
}
Result result=new Result();
Customer cu=new Customer();
cu.setEmail("[email protected]");
cu.setNick_name("王鹏");
result.setCustomer(cu);
net.sf.json.JSONObject fromObject = net.sf.json.JSONObject.fromObject(result); //json-lib 将对象转为json
System.out.println(fromObject);
String str = JSON.toJSONString(result);//fastjson 将对象转为json字符串 {"customer":{"email":"[email protected]","nick_name":"王鹏"}} {对象里面套对象}
System.out.println(str);
新手学习,有问题可以留言讨论。