JSON--Java与AJAX(Jquery)

一、JSON 是什么?
JSON 的全称是JavaScript Object Notation,是一种轻量级的数据交换格式。

JSON 与XML 具有相同的特性,例如易于人编写和阅读,易于机器生成和解析。但是JSON 比
XML 数据传输的有效性要高出很多。JSON 完全独立与编程语言,使用文本格式保存。
JSON 数据有两种结构:
• Name-Value 对构成的集合,类似于Java 中的Map。
• Value 的有序列表,类似于Java 中的Array。
一个JSON 格式的数据示例:
{
"Name": "Apple",
"Expiry": "2007/10/11 13:54",
"Price": 3.99,
"Sizes": [
"Small",
"Medium",
"Large"
]
}
更多关于JSON 数据格式的说明参看JSON 官方网站:http://www.json.org(中文
内容参看:http://www.json.org/json-zh.html

 

二、通过java来创建JSON对象

1.引入jar包

我这里使用的是json-lib-2.3-jdk15.jar,下载地址:http://sourceforge.net/projects/json-lib/files/

Json-lib requires (at least) the following dependencies in your classpath:

  • jakarta commons-lang 2.4
  • jakarta commons-beanutils 1.7.0
  • jakarta commons-collections 3.2
  • jakarta commons-logging 1.1.1
  • ezmorph 1.0.6

2.重要的对象及方法

1)JSONObject:JSON对象{}。

2)JSONArray:JSON数组对象,[{},{}]。

3)fromObject(object):将对象转换为JSON对象。

4)JSONObject.accumulate(key,value):向JSONObject中增加JSON数据,可以重复。

5)element(key,value):向JSON对象中增加JSON数据,如果重复后一个会替换前一个。

6)toString(i,i):将JSON对象转换为字符串,如果包含参数,是将其美化后输出。

 

以下是一个servlet输出JSON的例子:

package com.netqin.function.demo.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import com.netqin.function.demo.model.People;
import com.netqin.function.demo.model.Phone;

 

public class JsonServlet extends HttpServlet{
 private static final String CONTENT_TYPE = "text/plain; charset=UTF-8";

 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse response)
   throws ServletException, IOException {
  // TODO Auto-generated method stub
  this.StringToJson(req, response);
//  this.MapToJson(req, response);
//  this.BeanToJson(req, response);
//  this.ListToJson(req, response);
 }

 @Override
 protected void doPost(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  // TODO Auto-generated method stub
  doGet(req, resp);
 }
 
 /**                                                         
 * 描述 : <输出>. <br>
 *<p>                                                
                                                                                                                                                                                                      
 * @param response
 * @param content
 * @throws IOException                                                                                         
 */
 private void print(HttpServletResponse response,String content) throws IOException{
  response.setContentType(CONTENT_TYPE);
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        PrintWriter write = response.getWriter();
        write.print(content);
        write.close();
 }



 
 /**                                                         
 * 描述 : <将字符串或数组转换为JSON>. <br>
 *<p>                                                
                                                                                                                                                                                                      
 * @param req
 * @param response
 * @throws ServletException
 * @throws IOException                                                                                         
 */
// @SuppressWarnings("unused")
 private void StringToJson(HttpServletRequest req, HttpServletResponse response)throws ServletException, IOException{
  JSONObject resultJSON = new JSONObject();   
        try {   
         
            resultJSON.accumulate("name", "Violet")   
                      .accumulate("occupation", "developer")   
                      .accumulate("age", new Integer(22))
                      .accumulate("array", new int[] { 1, 2, 3 })
                      .accumulate("muliArray","[{'type': '你好', 'value': 'kelly@seankelly.biz'},{'type': 'home', 'pref': 1, 'value': 'kelly@seankelly.tv'}]");
   //System.out.println(resultJSON.toString(1,1));
  } catch (JSONException e) {
   e.printStackTrace();
  }
  this.print(response, resultJSON.toString(1,1));
  
 }

 

输出结果:

 {
  "name": "Violet",
  "occupation": "developer",
  "age": 22,
  "array":   [
   1,
   2,
   3
  ],
  "muliArray":   [
      {
    "type": "你好",
    "value": "kelly@seankelly.biz"
   },
      {
    "type": "home",
    "pref": 1,
    "value": "kelly@seankelly.tv"
   }
  ]
 }

 

 



 
 /**                                                         
 * 描述 : <将Map转换为JSON>. <br>
 *<p>                                                
                                                                                                                                                                                                      
 * @param req
 * @param response
 * @throws ServletException
 * @throws IOException                                                                                         
 */
 @SuppressWarnings("unchecked")
 private void MapToJson(HttpServletRequest req, HttpServletResponse response)throws ServletException, IOException{
  JSONObject resultJSON = null;   
  Map map = new HashMap(15);
        try {   
         map.put("name", "hanqf");
         map.put("age", 28);
         map.put("phone", "{home:135,busi:139}");
         resultJSON = JSONObject.fromObject(map);
   //System.out.println(resultJSON.toString());
  } catch (JSONException e) {
   e.printStackTrace();
  }
  this.print(response, resultJSON.toString(1,1));
 }


 输出结果:

 {
  "phone": "{home:135,busi:139}",
  "age": 28,
  "name": "hanqf"
 }

 

 



 
 /**                                                         
 * 描述 : <JavaBean转换为JSON>. <br>
 *<p>                                                
                                                                                                                                                                                                      
 * @param req
 * @param response
 * @throws ServletException
 * @throws IOException                                                                                         
 */
 private void BeanToJson(HttpServletRequest req, HttpServletResponse response)throws ServletException, IOException{
  JSONObject resultJSON = null;  
  People people = new People();
  Phone phone = new Phone("135","138");
        try {   
         people.setPhone(phone);
         resultJSON = JSONObject.fromObject(people);
   //System.out.println(resultJSON.toString());
  } catch (JSONException e) {
   e.printStackTrace();
  }
  this.print(response, resultJSON.toString(1,1));
 }

 

 

public class People{
 String name;
 int age;
 Phone phone = new Phone();

 

 setter and getter

 …………………………

}

 

public class Phone{
 String home;
 String busi;

 

 setter and getter

 …………………………

 

}

 

 

 输出结果:

 {
  "age": 0,
  "name": "",
  "phone":   {
   "busi": "138",
   "home": "135"
  }
 }


 
 /**                                                         
 * 描述 : <List转换为JSON>. <br>
 *<p>                                                
                                                                                                                                                                                                      
 * @param req
 * @param response
 * @throws ServletException
 * @throws IOException                                                                                         
 */
 private void ListToJson(HttpServletRequest req, HttpServletResponse response)throws ServletException, IOException{
  JSONArray jsonArray = null;  
  People people = null;
  Phone phone = null;
  List<People> list = new ArrayList<People>();
        try {   
         for(int i =0;i<3;i++){
          people = new People();
          phone = new Phone("135"+i,"138"+i);
          people.setAge(i);
          people.setPhone(phone);
          list.add(people);
         }
         jsonArray = JSONArray.fromObject(list);

   //System.out.println(jsonArray.toString());
  } catch (JSONException e) {
   e.printStackTrace();
  }
  this.print(response, jsonArray.toString(1,1));
 }
}
 输出结果:

 [
    {
   "age": 0,
   "name": "",
   "phone":    {
    "busi": "1380",
    "home": "1350"
   }
  },
    {
   "age": 1,
   "name": "",
   "phone":    {
    "busi": "1381",
    "home": "1351"
   }
  },
    {
   "age": 2,
   "name": "",
   "phone":    {
    "busi": "1382",
    "home": "1352"
   }
  }
 ]

 

三、Ajax调用

以<将字符串或数组转换为JSON>. 为例,

{
  "name": "Violet",
  "occupation": "developer",
  "age": 22,
  "array":   [
   1,
   2,
   3
  ],
  "muliArray":   [
      {
    "type": "你好",
    "value": "kelly@seankelly.biz"
   },
      {
    "type": "home",
    "pref": 1,
    "value": "kelly@seankelly.tv"
   }
  ]
}

 

jsp中主要的代码如下:

 

 <script type="text/javascript" src="jquery-1.2.6.pack.js"></script>

 

<script type="text/javascript">
jQuery(function($){


  $("#onebut").click(function(){

 

    $.getJSON("http://localhost:8080/points/json.do",function(data){


      $("#one").html("");
      $("#one").append(data.name);
      $("#one").append("##");
      $("#one").append(data.age);
      $("#one").append("##");
      $("#one").append(data.array[0]);
      //$("#one").append("##");
      //$("#one").append(data.muliArray[0].type);
   
      $.each(data.muliArray,function(i,item){
          $("#one").append("##");
          $("#one").append(item.type);
    
      }); 


   });


 });


});
</script>

 

 <button id="onebut">onebut</button>
 <div id="one"></div>

 

 

点击"onebut”按钮后,页面上显示如下:

Violet##22##1##你好##home
 

 四、JSON进阶

 

1.再来看几个重要的对象和方法

1)JSON:JSON对象的顶级接口,JSONObject,JSONArray都实现了该接口

2)JSONSerializer:JSON串行化对象

3)JSONSerializer.toJSON(object):将对象串行化为JSON

4)JSONSerializer.toJava(json):将JSON转换为对象

5)MorphDynaBean:JSONSerializer.toJava(json)后的值默认为MorphDynaBean

6)XMLSerializer:JSON转换为xml对象

7)xMLSerializer.write(json):将JSON对象转换为xml

8)xMLSerializer.read(xml):将xml转换为JSON对象

 

2.实例

 

 1)json转map

 

   JSONObject resultJSON = JSONObject.fromObject(map);

   Map mapp = (Map)JSONObject.toBean(resultJSON, Map.class);
   System.out.println(mapp.get("name"));


 

 

2)json转JavaBean

 

   JSONObject resultJSON =JSONObject.fromObject(people);

   People pp = (People)JSONObject.toBean(resultJSON, People.class);
   System.out.println(pp.getPhone().getBusi());


 

 

3)json转list

 

  JSONObject resultJSON = JSONConvert.generate(list);
    
  Map mapp = (Map)JSONObject.toBean(resultJSON, Map.class);
  List<MorphDynaBean> list2 = (List<MorphDynaBean>)mapp.get("root");
  for(MorphDynaBean pp : list2){
   System.out.println(((MorphDynaBean)pp.get("phone")).get("busi"));
  }

 

说明:

为什么没有使用JSONArray.toArray(jsonArray)或JSONArray.toCollection(jsonArray)呢?

笔者在使用过程中发现其在转换时不能对people.phone对象赋值,也就是说不能嵌套赋值,所以才改用map加MorphDynaBean的方式,也许是笔者没有搞明白,希望高手指点。

 

这里提供一个JSONConvert工具类,方便bean对象、map和list转换为JSONObject ,如下:

 

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

public class JSONConvert {

 public static JSONObject generate(List list) {

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("totalProperty", list.size());
        map.put("root", list);
        return JSONObject.fromObject(map);
    }

    public static JSONObject javabean2json(Object object) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("success", true);
        map.put("data", object);
        return JSONObject.fromObject(map);
    }

    public static JSONObject objectcollect2json(List list, String total) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("totalProperty", total);
        map.put("root", list);
        return JSONObject.fromObject(map);
    }

}


 

4)json转xml

 

需要引入该包:xom-1.1.jar,下载地址:http://repo1.maven.org/maven2/xom/xom/1.1/

 

  XMLSerializer xmlSe = new XMLSerializer();

  System.out.println("json=="+resultJSON.toString(1, 1));
  String xml = xmlSe.write(resultJSON);
  System.out.println("xml=="+xml);

 

输出结果:

json==

{
  "age": 0,
  "name": "",
  "phone":   {
   "busi": "139",
   "home": "135"
  }
 }
xml==

<?xml version="1.0" encoding="UTF-8"?>
<o>

<age type="number">0</age>

<name type="string"/>

<phone class="object">

<busi type="string">139</busi>

<home type="string">135</home>

</phone>

</o>


 5)json的特殊字符处理

由于json的格式要求,“:”“{}”,“[]”,“/”等等都是json的特定字符,

所以如果在name或value中出现了这些字符就会造成json解析异常,

比如:

 resultJSON.accumulate("phone", "{home:135,busi:139}");

在页面上的显示结果如下:

{
   "phone":   {
   "home": "135",
   "busi": 139
  }

}

如果json修改成如下形式:

resultJSON.accumulate("phone", "{home:135:11{[,busi:139}");

在页面上的显示结果如下:

{
   "phone": "{home:135:11{[,busi:139}",
}

此时,json会将"{home:135:11{[,busi:139}"都作为phone的值,而不会再向下解析

 

所以,在遇到这样的问题时只要将value用引号括起来就行了,如下:

resultJSON.accumulate("phone", "{home:'135:11{[',busi:139}");

 

输出结果如下:

{
   "phone":   {
   "home": "135:11{[",
   "busi": 139
  }

}

 

这样就可以正常解析了,所以,在创建json时,最好将name和value都用引号扩上。


 

 提供几个JSON的参考资料:

http://www.diybl.com/course/3_program/java/javashl/2007123/89756.html

 

http://developer.51cto.com/art/201001/176686.htm

 

http://www.javaeye.com/topic/78243


http://www.javaeye.com/topic/71343

 

另外,请特别关注如下资料,介绍的非常详细:

http://jiangzhengjun.javaeye.com/category/78136

 

 

 

 

 

 

 

 

 

 

 

 

 

 


 

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值