JSON 基础语法讲解,以及操作

来源:互联网 发布:恋母情结 知乎 编辑:程序博客网 时间:2024/06/15 14:18

JSON                    JavaScript Object  Notation一种简单的数据格式比xml更轻巧。JSON是JavaScript原生格式这意味着在JavaScript中处理JSON数据不需要任何特殊的API或工具包。      

JSON的规则很简单对象是一个无序的“ "名称/值" 对”集合。一个对象以“{”左括号开始“}”右括号结束。每个“名称”后跟一个“:”冒号“ "名称/值‟ 对”之间使用“,”逗号分隔。    

规则如下:         1映射用冒号“:”表示名称:值        

                         2并列的数据之间用逗号“ ,  ”分隔。名称1:值1,名称2:值2        

                         3 映射的集合对象用大括号“{}”表示。{名称1:值1,名称2:值2}        

                         4 并列数据的集合,数组,用方括号(“[ ]”)表示。     [       {名称1:值,名称2:值2},                {名称1:值,名称2:值2}             ]       

                         5  元素值可具有的类型string, number, object, array, true, false, null  

JSON 用冒号(而不是等号)来赋值。每一条赋值语句用逗号分开。整个对象用大括号封装起来。可用大括号分级嵌套数据。  对象描述中存储的数据可以是字符串数字或者布尔值。对象描述也可存储函数那就是对象的方法

 {  "Name":"Apple",

    "Expiry":"2007/10/1113:54",

    "Price":3.99,

    "Sizes":    [ "Small","Medium","Large" ]

 }

 

引用 HTTP 和 JSON支持

找到.gwt.xml文件,在其中的<inheritsname='com.google.gwt.user.User'/>

在之后添加如下的内容:<inheritsname="com.google.gwt.json.JSON"/>

                                       <inheritsname="com.google.gwt.http.HTTP"/>

其中com.google.gwt.json.JSON指的是要使用JSON,com.google.gwt.http.HTTP指得是通过HTTP调用服务器上的服务方法

 

组合一个包含数组类型的复杂JSON数据

        JSONObjectinput=newJSONObject();

        JSONStringvalue=newJSONString("mazhao");

        input.put("name",value);

        JSONArray  arrayValue=newJSONArray();

              arrayValue.set(0, newJSONString ("arrayitem0") );

              arrayValue.set(1, newJSONString ("arrayitem1") );

              arrayValue.set(2, newJSONString ("arrayitem2") );

        input.put("array",arrayValue);

JSON数据格式为:{  name:"mazhao",   array: {"arrayitem0","arrayitem1","arrayitem2"}  }

        注意上述的JSON类型的数据,使用的都是com.google.gwt.json.client包内的类型。这些类型最终会被编译为JavaScript执行

 

怎么解析JSON呢?针对上述中的复杂的JSON数据:  {name:"mazhao", array: {"arrayitem0","arrayitem1","arrayitem2"} }

   可以使用如下的方式解析:JSONObject  jsonObject=new  JSONObject (payload);          其中payload指的是上面的JSON格式的数据          

                                                   String name = jsonObject.getString("name");

                                                   System.out.println("name  is:" + name);

                                                   JSONArray  jsonArray=jsonObject.getJSONArray ("array");

                                                   for(inti=0;i<jsonArray.length();i++)

                                                             {   System.out.println("item" + i + " :" + jsonArray.getString(i) ) ;   }

        如何写GWT的Service来得到Payload的数据呢? 需要两点,第一,需要建立一个Service类,第二,覆盖父类的processCall方法         

       示例代码           

         package   com.jpleasure.gwt.json.server;

         import       com.google.gwt.user.client.rpc.SerializationException;

         import       com.google.gwt.user.server.rpc.RemoteServiceServlet;

         import       com.jpleasure.gwt.json.client.HelloWorldService;

         import       org.json.JSONArray;importorg.json.JSONException;

         import       org.json.JSONObject;

         public  class  HelloWorldServiceImpl  extends   RemoteServiceServlet   implements

                HelloWorldService{

                         public  String  processCall(Stringpayload)  throws  SerializationException {

                               try{

                                          JSONObject  jsonObject=new  JSONObject(payload);

                                          String  name = jsonObject.getString("name");

                                              System.out.println("name  is:" + name);

                                          JSONArray  jsonArray=jsonObject.getJSONArray("array");

                                          for(int i=0;i<jsonArray.length(); i++) {

                                                   System.out.println("item" + i + ":" + jsonArray.getString(i)  );

                                                      }

                                   }  catch (JSONException  e ) {

                                             e.printStackTrace();  //TochangebodyofcatchstatementuseFile  |  Settings | FileTemplates.

                                             }

                                                   return "success";

                               }

                         }

 

 JSON 语法例子:

   <script language="JavaScript">     

         var people ={             

                    "programmers": [    { "firstName": "Brett", "email": "b2222rett@1256.com" },             

                                                       { "firstName": "Jason",  "email": "ja22son@se233.com" },       

                                                       { "firstName": "Elliotte", "lastName":"Harold", "email": "el2222o@mq.com" }            

                                                  ],           

                          "authors":        [       { "firstName": "Isaac",  "genre": "science fiction" },      

                                                            { "firstName": "Tad", "genre": "fantasy" },             

                                                            { "firstName": "Frank",  "genre": "christian fiction" }            

                                                    ], 

                        "musicians":     [              { "firstName": "Eric",  "instrument": "guitar" },  

                                                                   { "firstName": "Sergei", "instrument": "piano" }            

                                                    ]};

                          window.alert(people.programmers[1].firstName);     

                          window.alert(people.musicians[1].instrument);  

          </script>

 

将Number表示为JSON就容易得多,利用Java的多态,我们可以处理Integer,Long,Float等多种Number格式:

          static  String  number2Json (Number  number)  {return  number.toString();  }

Boolean类型也可以直接通过toString()方法得到JSON的表示

          static  String  boolean2Json (Boolean  bool)  {return  bool.toString();  }

要将数组编码为JSON格式,可以通过循环将每一个元素编码出来

          static  String   array2Json ( Object[ ]  array ) {

                    if (array.length==0)

                             return"[]";

                     StringBuilder  sb = new  StringBuilder(array.length<<4);

                     sb.append('[');

                     for(Object  o : array ) {

                             sb.append ( toJson ( o ) ) ;

                             sb.append(',') ;

                             }

               //将最后添加的','变为']':

                    sb.setCharAt(sb.length()-1 , ']' );

                    return  sb.toString();

               }

              static  String  array2Json( Object[] array ) {

                            if (array.length==0)

                                   return"[]";

                            StringBuilder  sb = new  StringBuilder (array.length<<4);

                              sb.append('[');

                               for (Object  o:array ) {

                                             sb.append(toJson(o));

                                             sb.append(',');

                                              }       //将最后添加的','变为']':

                                sb.setCharAt(sb.length()-1, ']' );

                                returnsb.toString();

                  }