1.概念:JavaScript Object Notation JavaScript对象表示法
var p={"name":"zhangsan","age":23,"sex":"男"}
*json现在多用于储存和交换文本信息的语法
*进行数据的传输
*json比xml更小,更快,更易解析
2.语法:
//1.基本格式
var person = {"username":"张三","age":15};
alert(person)
//2.嵌套格式{}-->[]
var persons ={
"persons":[
{"username":"张三","age":15},
{"username":"李四","age":16},
{"username":"王五","age":17},
]
}
alert(persons);
//3.嵌套格式[]-->{}
var ps = [
{"username":"张三","age":15},
{"username":"李四","age":16},
{"username":"王五","age":17},
]
alert(ps);
1.基本规则
数据在名称/值对中
数据由逗号分隔
花括号保存对象
方括号保存数组
2.获取数据
var username = person.username;
alert(username);
var username1 = persons.persons[0].username;
alert(username1);
var age = ps[1].age;
alert(age)
3.遍历:
//for in 循环
for (var key in person){
//这样的方式获取不行。相当于person."username"
//alert(key+":"+person.key);
alert(key+":"+person[key]);
}
for (var i=0;i<ps.length;i++){
var p = ps[i];
for (var key in p){
alert(key+":"+p[key]);
}
}
3.JSON数据和Java对象的相互转换
*json解析器:
*常见的解析器:jsonlib,gson,fastjson,jackson
1.Java--->json
1.使用步骤:
1.导入jackson的相关jar包
2.创建Jackson核心对象,objectMapper
3.调用ObjectMapper的相关方法进行转换
public void test1() throws IOException {
//创建person对象
Person p = new Person();
p.setAge(15);
p.setName("张三");
//2创建核心对象 ObjectMapper
ObjectMapper mapper = new ObjectMapper();
//3.转换
/*
转换方法
writeValue
参数1:
File:将obj对象转换为json,并保存到指定文件中
Writer:将obj对象转换为json,并将数据填充到字符输出流中
OutputStream:将obj对象转换为json,并将json数据填充到字节输出流中
writeValueAsString(obj):将对象转为json字符串
*/
String s = mapper.writeValueAsString(p);
System.out.println(s);//{"name":"张三","age":15}
mapper.writeValue(new File("d://a.txt"),p);
mapper.writeValue(new FileWriter("d://b.txt"),p);
}
2.注解:
1.@JsonIgnore:忽略该属性
2.@JsonFormat:属性值格式化
//@JsonIgnore
@JsonFormat(pattern = "yyyy年MM月dd日")
private Date birth;
3.复杂Java对象转换
1.list
String s = mapper.writeValueAsString(list);
System.out.println(s);
2.map
Map<String,Object> map = new HashMap<String,Object>();
map.put("name","zhangsan");
map.put("age",14);
ObjectMapper mapper = new ObjectMapper();
String s = mapper.writeValueAsString(map);
System.out.println(s);
2.json--->java
1.使用步骤:
1.导入jackson的相关jar包
2.创建Jackson核心对象,objectMapper
3.调用ObjectMapper的相关方法进行转换
1.readValue
//1.初始化字符串
String JSON = "{\"age\":15,\"name\":\"张三\"}";
//2.创建objectmapper对象
ObjectMapper mapper = new ObjectMapper();
//3.转换为Java对象
Person person = mapper.readValue(JSON, Person.class);
System.out.println(person);
标签:username,mapper,age,json,person,JSON,var From: https://www.cnblogs.com/lin513/p/17054547.html