# Json数据的封装与解析
yc
- ## 后台封装
## Json数据格式
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。JSON采用完全独立于语言的文本格式,这些特性使JSON成为理想的数据交换语言。易于人阅读和编写,同时也易于机器解析和生成。不受语言的局限性。
### 基础结构
1.键值对{“key”,“value”},在不同的语言中它被理解为对象(object),记录(record),结构(struct),字典(dictionary),哈希表(hash table),有键列表(keyed list),或者关联数组 (associative array)。
```
{ "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" }
```
2.值的有序列表(An ordered list of values)。在大部分语言中,它被理解为数组(array)。
```
{ "people": [
{ "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" },
{ "firstName": "Jason", "lastName":"Hunter", "email": "bbbb"},
{ "firstName": "Elliotte", "lastName":"Harold", "email": "cccc" }
]}
```
```
{ "programmers": [
{ "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" },
{ "firstName": "Jason", "lastName":"Hunter", "email": "bbbb" },
{ "firstName": "Elliotte", "lastName":"Harold", "email": "cccc" }
],
"authors": [
{ "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" },
{ "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" },
{ "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" }
],
"musicians": [
{ "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" },
{ "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" }
] }
```
## 手动封装
```
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<User>users = new ArrayList<User>();
users.add(new User("U001" ,"张三", 20));
users.add(new User("U002" ,"李四", 21));
users.add(new User("U003" ,"王五", 22));
users.add(new User("U004" ,"赵六", 23));
String json ="";
//用java封装出json格式的字符串:[{name:"Jack",age:25}, {...}, {...} ]
for(User u: users){
if(json.equals("")){
/*
json = { "name":u.getName(),"id":u.getId(),"age":u.getAge()} ;
*/
json = "{ name:\""+u.getName()+"\",id:\""+u.getId()+"\",age:"+u.getAge()+"}" ;
}else{
json = json +",{ name:\""+u.getName()+"\",id:\""+u.getId()+"\",age:"+u.getAge()+"}" ;
}
}
json = "["+json+"]";
response.setCharacterEncoding("utf-8");
response.getWriter().print(json);
}
注:对一个对象,可以重写它的toString()方法;
```
## apache工具封装
先把把数据封装成Map
```
JSONObject obj = JSONObject.fromObject(map);
```
## fastjson工具封装
将list转成Json串
```
List<User>users = new ArrayList<User>();
users.add(new User("U001" ,"张三", 20));
users.add(new User("U002" ,"李四", 21));
users.add(new User("U003" ,"王五", 22));
users.add(new User("U004" ,"赵六", 23));
//用fastjson工具(只有一个jar包)帮我们把list转换成json串
String strJson= JSON.toJSONString(users);
```
## 解析
使用jQuery的.getJSON()直接解析
```
$.getJSON("SelectFilesServlet.do?filesName="+textValue, function(data){
$.each(data, function(i,item){
$("#div-show").append("<span>"+item.fileName+"</span><br>");
});
});
```