map.set('key1','value1')
map.set('key2','value2')
// Map 转 JSON字符串
let map_string = JSON.stringify([...map])
console.log('map ->json:',map_string)
// JSON字符串转map
let obj = JSON.parse(map_string)
let new_map = new Map()
for(let key of Object.keys(obj)){
new_map.set(key,obj[key])
}
console.log('json ->map:',new_map)
JavaBean(以User为例)转成json格式1.转成JSONArray类型
User user = new User()
user.setUsername("cxl")
user.setPassword("1234")
JSONArray json = JSONArray.fromObject(user)
System.out.println(json)//[{"password":"1234","username":"cxl"}]
response.getWriter().print(json.toString())
在js文件取数据
$.getJSON("http://localhost:8080/jQueryDemo/servlet/UserServlet",null,function(data) {
alert(data[0].username)
alert(data[0].password)
})
2.转成JSONObject类型
JSONObject jsonObj = JSONObject.fromObject(user)
System.out.println(jsonObj)//{"password":"1234","username":"cxl"}
response.getWriter().print(jsonObj)
在js文件取数据
alert(data.username)
alert(data.password)
List转成json格式
List<User>users = new ArrayList<User>()
User user = new User()
user.setUsername("cxl")
user.setPassword("1234")
User u = new User()
u.setUsername("lhl")
u.setPassword("1234")
users.add(user)
users.add(u)
1.转成JSONArray类型
JSONArray json = JSONArray.fromObject(users)
System.out.println(json.toString())
//[{"password":"1234","username":"cxl"},{"password":"1234","username":"lhl"}]
response.getWriter().print(json.toString())
js中取数据:alert(alert(data[0].username))