JSON数据的简介及相关操作

     JSON是一种很简洁很重要的数据格式,通常用来交换传输数据,广泛使用于JavaScript技术中,并逐渐在各种流行编程语言中火了起来。在Java中也有一个JSON的库,用来重要作用就是Java对象与JSON、XML数据的相互转换,有着重要的应用。

     JSON结构的格式就是若干个 键/值(key, value) 对的集合,该集合可以理解为字典(Dictionary),每个 键/值 对可以理解成一个对象(Object)。 键/值 对中的 键(key) 一般是 一个string,值(value)可以是string、double、int等基本类型,也可以嵌套一个 键/值 对,也可以是一个数组,数组里面的数据的类型可以是基本类型,或者 键/值 对。可以看出 键/值 本来没什么,只是嵌套得多了就会觉得混乱,下面举个具体的例子来说明。注:该代码只是用来举例说明,并不能正确运行。

复制代码
 1             var testJson = {                      
2 "Name" : "奥巴马" ,
3 "ByName" : ["小奥","小巴","小马"],
4 "Education" : {
5 "GradeSchool" : "华盛顿第一小学",
6 "MiddleSchool" : ["华盛顿第一初中" , "华盛顿第一高中"],
7 "University" : {
8 "Name" : "哈佛大学",
9 "Specialty" : ["软件工程","会计"]
10 }
11 }
12 }
复制代码

变量testJson就是一个json对象,testJson对象包括三个 键/值 对。

第一个 键/值 对: 键(key)是"Name“ ,其对应的值(value)是 "奥巴马" ,即 testJson["Name"]  == "奥巴马"

第二个 键/值 对: 键 是 "ByName" ,值是一个数组,是一个string集合。有必要的话,数组里面的元素也可以是 键/值 对。

第三个 键/值 对: 键 是 "Education",值是一个 Json对像,该json对象包括三个 键/值 对,这就是嵌套了。。。

总结:json对象就是若干个 键/值 对的集合,键是string,值可以是基本类型,或者嵌套一个Json对象,或者是一个数组(数组里的元素可以是基本类型,也可以是json对象,可以继续嵌套)。

获取名字:testJson["Name"]

获取第一个别名:testJson["ByName"][0] 。testJson的 键"ByName" 对应的值 是一个string数组 

获取小学名字: testJson["Education"]["GradeSchool"] , 获取大学主修专业:testJson["Education"]["University"]["Specialty"][0]

 

下面举个实例:

定义一个符合json格式要求的字符串:

string testJson = "{\"Name\" : \"奥巴马\",\"ByName\" : [\"小奥\",\"小巴\",\"小马\"],\"Education\":{\"GradeSchool\" : \"华盛顿第一小学\",\"MiddleSchool\" : [\"华盛顿第一初中\" , \"华盛顿第一高中\"], \"University\" :{ \"Name\" : \"哈佛大学\", \"Specialty\" : [\"软件工程\",\"会计\"]}}}";

然后需要用该字符串作为参数new 一个 JsonObject对象。微软自带的类库 System.Json ,然后添加命名空间 using System.Json;

主要代码就一句:JsonObject js = JsonObject.Parse(testJson); 用字符串testJson 作为参数new 一个 JsonObject 对象。通过监视我们可以看到js里面的内容和预料的一样,通过下面这幅图你应该可琢磨出很多东西来吧

 

额外插一句:js["Education"]["University"]["Specialty"] 的内容是 {[  "软件工程",  "会计"]},

但js["Education"]["University"]["Specialty"].Contains( "软件工程") 的值 是false。原因自己琢磨

 

  开源的JSON库主页:http://json-lib.sourceforge.net/

  环境:JDK5 , json-lib-2.3-jdk15

  所依赖的包:json-lib-2.3-jdk15.jar,commons-collections.jar,commons- lang.jar,commons-logging.jar,commons-beanutils.jar,ezmorph-1.0.6.jar,xom-1.1.jar

  java中各种类型所对应的json格式:

  1.数组或集合-->JSON串

  public static void test1() {

  System.out.println("------------数组或集合-->JSON串----------");

  boolean[] boolArray = new boolean[]{true, false, true};

  JSONArray jsonArray1 = JSONArray.fromObject(boolArray);

  System.out.println(jsonArray1);

  //输出格式: [true,false,true]

  List list = new ArrayList();

  list.add("first");

  list.add("second");

  JSONArray jsonArray2 = JSONArray.fromObject(list);

  System.out.println(jsonArray2);

  //输出格式: ["first","second"]

  JSONArray jsonArray3 = JSONArray.fromObject("['json','is','easy']");

  System.out.println(jsonArray3);

  //输出格式: ["json","is","easy"]

  }

  2.Object|Map-->JSON串

  public static void test2() {

  System.out.println("------------Object|Map-->JSON串----------");

  Map map = new HashMap();

  map.put("name", "json");

  map.put("bool", Boolean.TRUE);

  map.put("int", new Integer(1));

  map.put("arr", new String[]{"a", "b"});

  map.put("func", "function(i){ return this.arr[i]; }");

  JSONObject jsonObject1 = JSONObject.fromObject(map);

  System.out.println(jsonObject1);

  //输出格式: {"func":function(i){ return this.arr[i]; },"arr":["a","b"],"int":1,"bool":true,"name":"json"}

  JSONObject jsonObject2 = JSONObject.fromObject(new MyBean());

  System.out.println(jsonObject2);

  //输出格式: {"func1":function(i){ return this.options[i]; },"func2":function(i){ return this.options[i]; },"name":"json","options":["a","f"],"pojoId":1}

  }

  public class MyBean {

  private String name = "json";

  private int pojoId = 1;

  private char[] options = new char[]{'a', 'f'};

  private String func1 = "function(i){ return this.options[i]; }";

  private JSONFunction func2 = new JSONFunction(new String[]{"i"}, "return this.options[i];");

  public String getName() {

  return name;

  }

  public void setName(String name) {

  this.name = name;

  }

  public int getPojoId() {

  return pojoId;

  }

  public void setPojoId(int pojoId) {

  this.pojoId = pojoId;

  }

  public char[] getOptions() {

  return options;

  }

  public void setOptions(char[] options) {

  this.options = options;

  }

  public String getFunc1() {

  return func1;

  }

  public void setFunc1(String func1) {

  this.func1 = func1;

  }

  public JSONFunction getFunc2() {

  return func2;

  }

  public void setFunc2(JSONFunction func2) {

  this.func2 = func2;

  }

  }

3.JSON串-->Object

  public static void test3() {

  System.out.println("------------JSON串-->Object----------");

  String json1 = "{name=\"json\",bool:true,int:1,double:2.2,func:function(a){ return a; },array:[1,2]}";

  JSONObject jsonObject1 = JSONObject.fromObject(json1);

  Object bean1 = JSONObject.toBean(jsonObject1);

  System.out.println(bean1);

  //net.sf.ezmorph.bean.MorphDynaBean@10dd1f7[

  //    {double=2.2, func=function(a){ return a; }, int=1, name=json, bool=true, array=[1, 2]}

  //]

  String json2 = "{bool:true,integer:1,string:\"json\"}";

  JSONObject jsonObject2 = JSONObject.fromObject(json2);

  BeanA bean2 = (BeanA) JSONObject.toBean(jsonObject2, BeanA.class);

  System.out.println(bean2);

  // BeanA{bool=true, integer=1, string='json'}

  }

  public class BeanA {

  private boolean bool;

  private Integer integer;

  private String string;

  public boolean isBool() {

  return bool;

  }

  public void setBool(boolean bool) {

  this.bool = bool;

  }

  public Integer getInteger() {

  return integer;

  }

  public void setInteger(Integer integer) {

  this.integer = integer;

  }

  public String getString() {

  return string;

  }

  public void setString(String string) {

  this.string = string;

  }

  @Override

  public String toString() {

  return "BeanA{"bool=" + bool +", integer=" + integer +", string='" + string + '\'' +"}";

  }

  }

  4.JSON串-->XML

  public static void test4() {

  System.out.println("------------JSON串-->XML----------");

  JSONObject json = new JSONObject(true);

  String xml = new XMLSerializer().write(json);

  System.out.println(xml);

  JSONObject json1 = JSONObject.fromObject("{\"name\":\"json\",\"bool\":true,\"int\":1}");

  String xml1 = new XMLSerializer().write(json1);

  System.out.println(xml1);

  JSONArray json2 = JSONArray.fromObject("[1,2,3]");

  String xml2 = new XMLSerializer().write(json2);

  System.out.println(xml2);

  }

  5.XML-->JSON串

  public static void test5() {

  System.out.println("------------XML-->JSON串----------");

  String xml = "" +

  "<a class=\"array\">\n" +

  "    <e type=\"function\" params=\"i,j\">\n" +

  "            return matrix[i][j];\n" +

  "    </e>\n" +

  "</a>";

  JSONArray json = (JSONArray) new XMLSerializer().read(xml);

  System.out.println(json);

  }

  特别注意:

  1、所有的Bean都应该定义为public,否则会出现net.sf.json.JSONException: java.lang.NoSuchMethodException: Property '***' has no getter method的错误。

  2、必须引入xom-1.1.jar包,否则抛出java.lang.NoClassDefFoundError: nu/xom/Serializer

posted @ 2012-07-09 09:15  学无先后 达者为先  阅读(640)  评论(1编辑  收藏  举报