JSON扫盲帖

2024-04-01 10:08
文章标签 json 扫盲

本文主要是介绍JSON扫盲帖,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

[心得] JSON扫盲帖+JSON类教程

昨天发了json的AS3解析类,从大家的跟帖上来看,好多人还是不知道这个东西的,特建一个扫盲贴。
其实在AS中使用json其实并不是一个必须或是很好的选择,因为AS对xml的解析已经很不错了,但是为什么可以考虑使用json呢,有以下几点:
  • json是介于单纯的文本方式(如:firstName=Brett&lastName=McLaughlin&email=brett@newInstance.com)和xml(<request><firstName>Brett</firstName><lastName>McLaughlin</lastName><email>brett@newInstance.com</email></request>)中间的一种格式,他具有文本和xml的中性优势:数据量小和清晰的数据格式。
  • json是JavaScript Object Notation的简写,那么意思就是说他是来自于javascript的东西。因为现在ajax的流行,大部分网站会采用ajax的模式和构架,那么json会是一个数据传输的首选(文本方式太简单,要是大数据量的时候无法理解,xml的方式数据量大,在解析的时候会增加服务器负担),那么要是一个网站从ajax构架的基础上出一个flex/flash版的界面的时候使用json会最少地减少服务器端的程序改动。
  • 服务器端现在有成熟的JSON解析代码(因为JSON运用太广泛了),那么在开发的时候也不用担心服务器端的解析。
ps:我怎么只能想到上面三点啊,会不会理由太少了?

JSON 是什么?

简单 JSON 示例
按照最简单的形式,可以用下面这样的 JSON 表示名称/值对:
  1. { "firstName": "Brett" }
复制代码
这个示例非常基本,而且实际上比等效的纯文本名称/值对占用更多的空间:
  1. firstName=Brett
复制代码
但是,当将多个名称/值对串在一起时,JSON 就会体现出它的价值了。首先,可以创建包含多个名称/值对的记录,比如:
  1. { "firstName": "Brett", "lastName":"McLaughlin", "email": "brett@newInstance.com" }
复制代码
从语法方面来看,这与名称/值对相比并没有很大的优势,但是在这种情况下 JSON 更容易使用,而且可读性更好。例如,它明确地表示以上三个值都是同一记录的一部分;花括号使这些值有了某种联系。

值的数组
当需要表示一组值时,JSON 不但能够提高可读性,而且可以减少复杂性。例如,假设您希望表示一个人名列表。在 XML 中,需要许多开始标记和结束标记;如果使用典型的名称/值对(就像在本系列前面文章中看到的那种名称/值对),那么必须建立一种专有的数据格式,或者将键名称修改为 person1-firstName 这样的形式。
如果使用 JSON,就只需将多个带花括号的记录分组在一起:
  1. { "people": [
  2.   { "firstName": "Brett", "lastName":"McLaughlin", "email": "brett@newInstance.com" },
  3.   { "firstName": "Jason", "lastName":"Hunter", "email": "jason@servlets.com" },
  4.   { "firstName": "Elliotte", "lastName":"Harold", "email": "elharo@macfaq.com" }
  5. ]}
复制代码
这不难理解。在这个示例中,只有一个名为 people 的变量,值是包含三个条目的数组,每个条目是一个人的记录,其中包含名、姓和电子邮件地址。上面的示例演示如何用括号将记录组合成一个值。当然,可以使用相同的语法表示多个值(每个值包含多个记录):
  1. { "programmers": [
  2.   { "firstName": "Brett", "lastName":"McLaughlin", "email": "brett@newInstance.com" },
  3.   { "firstName": "Jason", "lastName":"Hunter", "email": "jason@servlets.com" },
  4.   { "firstName": "Elliotte", "lastName":"Harold", "email": "elharo@macfaq.com" }
  5. ],
  6. "authors": [
  7.   { "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" },
  8.   { "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" },
  9.   { "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" }
  10. ],
  11. "musicians": [
  12.   { "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" },
  13.   { "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" }
  14. ]
  15. }
复制代码
这里最值得注意的是,能够表示多个值,每个值进而包含多个值。但是还应该注意,在不同的主条目(programmers、authors 和 musicians)之间,记录中实际的名称/值对可以不一样。JSON 是完全动态的,允许在 JSON 结构的中间改变表示数据的方式。
在处理 JSON 格式的数据时,没有需要遵守的预定义的约束。所以,在同样的数据结构中,可以改变表示数据的方式,甚至可以以不同方式表示同一事物。

ps:以上例子都是来自http://www.ibm.com/developerworks/cn/web/wa-ajaxintro10/掌握 Ajax,自己懒,看人家有就顺便用了


当当当,我又回来了,上周忙这上班没顾上写用法,下面就介绍一下adobe的json类的用法。
上次发表的json类有问题(http://bbs.actionscript3.cn/thread-1625-1-1.html),因为我也是从别人处下载的,谁知道是一个半成品。望大家别生气啊,建议管理员给删除了!
这次是adobe的官方的类,我修改了一下包,这次就可以用了。

下面是教程,比较简单:
1、服务器端来的json
怎么样获得服务器端的json我就不说了吧(就是通讯),那么得到的应该是一个字符串,存入变量serverJSON,使用方式如下:
  1. import json.*;
  2. var json:Object = new Object();
  3. json = JSON.decode(serverJSON);
复制代码

json就是一个对象了,简单吧。
举一个例子:
上面的JSON的一段代码:
  1. { "programmers": [
  2.   { "firstName": "Brett", "lastName":"McLaughlin", "email": "brett@newInstance.com" },
  3.   { "firstName": "Jason", "lastName":"Hunter", "email": "jason@servlets.com" },
  4.   { "firstName": "Elliotte", "lastName":"Harold", "email": "elharo@macfaq.com" }
  5. ],
  6. "authors": [
  7.   { "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" },
  8.   { "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" },
  9.   { "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" }
  10. ],
  11. "musicians": [
  12.   { "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" },
  13.   { "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" }
  14. ]
  15. }
复制代码
存入变量:serverJSON

代码:
  1. var serverJSON:String = '{ "programmers": [{ "firstName": "Brett", "lastName":"McLaughlin", "email": "brett@newInstance.com" },{ "firstName": "Jason", "lastName":"Hunter", "email": "jason@servlets.com" }, { "firstName": "Elliotte", "lastName":"Harold", "email": "elharo@macfaq.com" }],"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" }]}'
  2. var s:Object = JSON.decode(serverJSON);
  3. //开始使用
  4. trace(s.programmers[0].firstName);//输出:Brett
复制代码

不是吧这么简单。其实转变后就成为一个对象了,可以通过点语法来访问这些值了。XML靠边去。
2、本地对象做成JSON
你要是能自己拼出JSON字符串也可以,不过我们是在面向对象的世界啊,那么我们都是对象啊,到时候对象直接就可以来用了。
举一个例子:
  1. import json.*;
  2. var myObject:Object = new Object();
  3. myObject.ab = "adfsdf";
  4. myObject.cd = Math.random();
  5. trace(JSON.encode( myObject ));//输出:{"ab":"adfsdf","cd":0.0599129400216043}
复制代码

这样就可以给服务器了。
总结:就两个方法,JSON.decode(String),JSON.encode(Object),有这么简单的方式实现传输量小,而且简单的数据格式,我们为什么还不用呢?
其实XML自然也有他自己的强势,当一个结构复杂的数据结构出现的时候,这个时候JSON就很难搞定了,XML就是首选了。


在Flex中使用Json (转载收藏)


    要用到JSON,看了一篇(http://bbs.actionscript3.cn/thread-1657-1-1.html )的扫盲贴,在Flex中使用Json十分方便。json是介于纯文本方式与xml方式之间的一种格式,json能做到的事情,xml完成可以做到。为什么要用json呢,我看大部分还是像我一样,不得不用。json是ajax数据传输的首选,现有的项目使用的已经是json,如果增加flex界面时也使用json,那改动就会非常少。扫盲贴中说出的三个理由,我觉得这一个最充分。

    要在flex中使用json,首先要下一个json包。是官方的,却在官方怎么也载不下来。终于在CSDN上用了3分才down下来。放在附件中,需要的可以拿去用。

    贴一个例子:

<? xml version="1.0" encoding="utf-8" ?>
< mx:Application  xmlns:mx ="http://www.adobe.com/2006/mxml" layout ="absolute"
 creationComplete ="init()" >
     < mx:Script >
         <![CDATA[
              
            import com.adobe.serialization.json.*;  
              
              
            private var jsonStr:String;  
            private var jsonObj:Object;           
              
            private var jsonObj2:Object;  
            private var jsonStr2:String;  
              
            internal function init():void{  
                jsonStr =  '{"name":"zhanzhihu","age":22,"gender":"male"}';               
                jsonObj = new Object();  
                jsonObj = JSON.decode(jsonStr);  
                trace(jsonObj.name);  
                  
                jsonObj2 = new Object();  
                jsonObj2.firstName = "bill";  
                jsonObj2.lastName  = "Gate";      
                jsonObj2.com       = "Microsoft";  
                jsonStr2 = JSON.encode( jsonObj2 );  
                trace( jsonStr2 );       
            }  
                          
         ]]>
     </ mx:Script >
</ mx:Application >

 

输出为:

zhanzhihu
{"firstName":"bill","lastName":"Gate","com":"Microsoft"}

jsonStr是一个json格式的字符串,用JSON.decode(String)便可以将它解析为as对象,同样用JSON.encode(Object)可以将as对象转为json字符串,flex前台对json的操作真是方便。

 

corelib下载地址:http://code.google.com/p/as3corelib/

分类:  Flex 练习


[转]Flex用JSON处理返回的数据

关键字: flex json
FLEX处理返回的数据,然后绑定有很多种方法.不过看牛人们一般都是对数据进行处理成对象,再绑定到数据集.可能是这样更符合面向对象,也更合乎规范。用JSON对那些牛人来讲可能是方便不少,数据条理也相对清晰很多.
xml 代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns="*" layout="absolute"  
  3.     creationComplete="service.send()">  
  4.   
  5.     <mx:Script>  
  6.         <![CDATA[ 
  7.             import mx.collections.ArrayCollection; 
  8.             import mx.rpc.events.ResultEvent; 
  9.             import com.adobe.serialization.json.JSON; 
  10.  
  11.             private function onJSONLoad(event:ResultEvent):void 
  12.             { 
  13.                 //get the raw JSON data and cast to String 
  14.                 var rawData:String = String(event.result); 
  15.  
  16.                 //decode the data to ActionScript using the JSON API 
  17.                 //in this case, the JSON data is a serialize Array of Objects. 
  18.                 var arr:Array = (JSON.decode(rawData) as Array); 
  19.  
  20.                 //create a new ArrayCollection passing the de-serialized Array 
  21.                 //ArrayCollections work better as DataProviders, as they can 
  22.                 //be watched for changes. 
  23.                 var dp:ArrayCollection = new ArrayCollection(arr); 
  24.  
  25.                 //pass the ArrayCollection to the DataGrid as its dataProvider. 
  26.                 grid.dataProvider = dp; 
  27.  
  28.             } 
  29.         ]]>  
  30.     </mx:Script>  
  31.   
  32.     <mx:HTTPService id="service" resultFormat="text"  
  33.                     url="http://weblogs.macromedia.com/mesh/mashedpotato.json"  
  34.                     result="onJSONLoad(event)" />  
  35.   
  36.     <mx:DataGrid id="grid" right="10" left="10" top="10" bottom="10">  
  37.         <mx:columns>  
  38.             <mx:DataGridColumn headerText="Service" dataField="src"/>  
  39.             <mx:DataGridColumn headerText="Title" dataField="title"/>  
  40.         </mx:columns>  
  41.     </mx:DataGrid>  
  42. </mx:Application>  

 

 





 

 

 

使用Flex,Java,Json更新Mysql数据【1】
一直都只有看到从Mysql读取数据到Flex app中然后显示在DataGrid控件中。还很少见到从Flex app中的Datagrid取得数据写回数据库的例子。在网上搜索了找到一篇用Flex,PHP,JSON的方法:具体请参考: Using Flex, PHP, and JSON to Modify a MySQL Database。写的非常的简单明白,可惜的是自己没学过PHP。无法按照例子上完整的去实现,所以我把它更改用Java-Json的方法来实现同样的功能。
首先来看下这个例子的界面功能设计:包含一个dataGrid控件,两个按钮(读取和更新数据)以及一个Label控件用来提示用户操作的结果。dataGrid包含四个列:员工的编号,姓名,性别以及部门。其中姓名这个列是可以编辑修改的:编辑后通过检查后,按更新按钮更新数据库。

接着来看下工作流程:Flex app是通过remoteObject方式与后台的java bean沟通的,然后在由java bean连接mysql database,读取或更新数据。然后返回给flex app. 由于使用blazeDS,flex app可以直接调用java 的方法,所以发送请求和接受数据都变的简单了。
那么,我门开始工作了。
首先,创建一个数据库:在mysql提示框中输入以下的SQL就可以创建一个简单的员工信息资料表。

CREATE DATABASE IF NOT EXISTS test;
USE test;

DROP TABLE IF EXISTS `employee`;
CREATE TABLE `employee` (
  `id` varchar(10) NOT NULL,
  `name` varchar(45) NOT NULL,
  `gender` varchar(10) NOT NULL,
  `department` varchar(45) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

我们来先看看那后台java bean的处理:他要接受flex app的读取数据和更新数据的请求,而且他们之间的数据传递格式采用的是json.所以我们的java bean的一个框架结构应该是:

public class JsonGrid {
    private Connection con = null;
    private String myDriver = "com.mysql.jdbc.Driver";
    private String conURL = "jdbc:mysql://localhost:3306/test";
    private String userName = "root";
    private String userPass = "12345";
     
    public Connection conToDB(){
         try{
             Class.forName(myDriver);
             con = DriverManager.getConnection(conURL,userName,userPass);
         }catch(Exception e){
             e.printStackTrace();
         }
         return con;
     }
    public String getJsonArray(){
        String result= new String();        
        return result;
    }
    public String sendJsonArray(String jsonData){
        String result= new String();
     return result; 
    }
}

里面包含了两个重要的方法(getJsonArray()和sendJsonArray())分别对应flex app的读取数据和更新数据的请求。在getJsonArray()方法中,要连接数据库,取得员工的信息资料,然后按照json格式封装数据,结果返回给flex app,由flex app中的datagrid显示出来。我们具体看看getJsonArray()这个方法:

    public String getJsonArray(){
        JSONArray jsonEmployeeArray = new JSONArray();
        ResultSet rs = null;
        String result= new String();
        try{
             Connection conToDb = conToDB();
             Statement stmt = conToDb.createStatement();
             rs=stmt.executeQuery("select * from employee");
             while(rs.next()){
                 JSONObject jsonEmployee = new JSONObject();
                 jsonEmployee.put("id", rs.getString("id"));
                 jsonEmployee.put("name", rs.getString("name"));
                 jsonEmployee.put("gender", rs.getString("gender"));
                 jsonEmployee.put("department", rs.getString("department"));
                 jsonEmployeeArray.add(jsonEmployee);
             }
             result = jsonEmployeeArray.toString();
             conToDb.close();
             //result = new JSONObject().put("jsonEmployeeArray",jsonEmployeeArray).toString();

             }catch(SQLException ex){
                 ex.printStackTrace();
             }
        
        return result;
    }

内容其实都很简单,只是读取数据和封装成json格式的数据,最后把json array格式的jsonEmployeeArray转换成string格式传输给flex app.即return语句。而当flex app要使用这个json array格式的数据,自然需要按照json格式解码等,后面在介绍。接着看看那个更新数据的方法sendJsonArray():

public String sendJsonArray(String jsonData){
        String result= new String();
        //jsonData = jsonData.replace("//", "");

     JSONArray jsonArray = JSONArray.fromObject(jsonData);
     
     try{
         Connection conToDb = conToDB();
         Statement stmt = conToDb.createStatement();
     for(int i=0;i<jsonArray.size();i++){
         JSONObject jsonObject = JSONObject.fromObject(jsonArray.getString(i));
         String id = jsonObject.getString("id");
         String name = jsonObject.getString("name");
         stmt.executeUpdate("update employee set name='"+name+"' where id='"+id+"'");
     }
     result="恭喜,成功更新数据!";
     conToDb.close();
     }catch(Exception e){
         e.printStackTrace();
     }
     return result; 
    }

即把flex app传递过来的String类型的json格式的的数据解码开来,然后根据对应的Id把更新后的名字保存在数据库中。这里我们传递过来的是整个datagrid的信息,不管是有没有更新的,都要循环的更新所有员工的信息。所以呢,在你的程序中你的JsonGrid.java文件应该类似:

package jsongrid;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

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

public class JsonGrid {
    private Connection con = null;
    private String myDriver = "com.mysql.jdbc.Driver";
    private String conURL = "jdbc:mysql://localhost:3306/test";
    private String userName = "root";
    private String userPass = "liceven";
     
    public Connection conToDB(){
         try{
             Class.forName(myDriver);
             con = DriverManager.getConnection(conURL,userName,userPass);
         }catch(Exception e){
             e.printStackTrace();
         }
         return con;
     }
    public String getJsonArray(){
        JSONArray jsonEmployeeArray = new JSONArray();
        ResultSet rs = null;
        String result= new String();
        try{
             Connection conToDb = conToDB();
             Statement stmt = conToDb.createStatement();
             rs=stmt.executeQuery("select * from employee");
             while(rs.next()){
                 JSONObject jsonEmployee = new JSONObject();
                 jsonEmployee.put("id", rs.getString("id"));
                 jsonEmployee.put("name", rs.getString("name"));
                 jsonEmployee.put("gender", rs.getString("gender"));
                 jsonEmployee.put("department", rs.getString("department"));
                 jsonEmployeeArray.add(jsonEmployee);
             }
             result = jsonEmployeeArray.toString();
             conToDb.close();
             //result = new JSONObject().put("jsonEmployeeArray",jsonEmployeeArray).toString();

             }catch(SQLException ex){
                 ex.printStackTrace();
             }
        
        return result;
    }
    public String sendJsonArray(String jsonData){
        String result= new String();
        //jsonData = jsonData.replace("//", "");

     JSONArray jsonArray = JSONArray.fromObject(jsonData);
     
     try{
         Connection conToDb = conToDB();
         Statement stmt = conToDb.createStatement();
     for(int i=0;i<jsonArray.size();i++){
         JSONObject jsonObject = JSONObject.fromObject(jsonArray.getString(i));
         String id = jsonObject.getString("id");
         String name = jsonObject.getString("name");
         stmt.executeUpdate("update employee set name='"+name+"' where id='"+id+"'");
     }
     result="恭喜,成功更新数据!";
     conToDb.close();
     }catch(Exception e){
         e.printStackTrace();
     }
     return result; 
    }
}

接下来我们看看flex app前台的处理。
请见: 使用Flex,Java,Json更新Mysql数据【2】  



使用Flex,Java,Json更新Mysql数据【2】
前面我们已经说过了后 台java bean的处理,接着我们讲前台flex app的处理。flex app界面包含一个datagrid,两个button和一个Label。所以前台的JsonGrid.mxml代码设计如下:

<mx:Panel title="员工信息管理" x="61" y="41" width="476" height="385" layout="absolute">
        <mx:DataGrid id="dgData" toolTip="姓名可编辑" x="10" y="10" width="436" height="250" dataProvider="{dataArray}"
             creationComplete="{initDataGrid()}" editable="true" itemEditEnd="{checkName(event)}"verticalScrollPolicy="on">
            <mx:columns>
                <mx:DataGridColumn headerText="编号" dataField="id" editable="false"/>
                <mx:DataGridColumn headerText="姓名*" dataField="name" editable="true"/>
                <mx:DataGridColumn headerText="性别" dataField="gender" editable="false"/>
                <mx:DataGridColumn headerText="部门" dataField="department" editable="false"/>
            </mx:columns>
        </mx:DataGrid>
        <mx:Label id="lblStatus" x="27" y="305" width="372" height="25" fontFamily="Times New Roman"fontSize="13" color="#BF03FD"/>
        <mx:Button id="getJson" label="读取" toolTip="读取员工数据" x="61" y="268" width="74" height="29"click="getDataAction()"/>
        <mx:Button id="sendJson" x="254" y="268" label="更新" height="29" click="sendDataAction()"width="74"/>
    </mx:Panel>

界面设计好了之后,我们开始做读取数据的处理。我们采用的是remoteObject的方法所以,在mxml中添加<mx:RemoteObject>,destination指定的为后台java bean中的json.JsonGrid中的getJsonArray()这个方法。

<mx:RemoteObject id="getData" destination="getJsonData" source="jsongrid.JsonGrid" showBusyCursor="true"result="getJsonData(event)">
     <mx:method name="getJsonArray" result="getJsonData(event)"/>
    </mx:RemoteObject>

由于getJsonArray方法返回的是一个array类型的数据,所以我们要在mxml中的AS定义一个dataArray,同时这个dataArray也作为datagrid的一个data provier.我们的设计是在程序加载的时候自动读取数据,所以要在在<mx:DataGrid>中使用了creationComplete="{initDataGrid()}" 来初始化这个dataArray,以及执行读取数据的功能和对结果进行处理:

<mx:Script>
    <![CDATA[
        import mx.events.DataGridEvent;
        import mx.controls.TextInput;
        import mx.rpc.events.ResultEvent;
        import mx.collections.ArrayCollection;
        import com.adobe.serialization.json.JSON;
        
        [Bindable]
        private var dataArray:ArrayCollection;
        
        private function initDataGrid():void{
            dataArray = new ArrayCollection();
     getData.getOperation('getJsonArray').send();
        }
        
        private function getDataAction():void{
            getData.getJsonArray();
            lblStatus.text="正在读取...请稍候";
        }
        private function getJsonData(event:ResultEvent):void{
            var rawArray:Array;
            var arraySize:int;
            var rawData:String = event.result as String;
            rawArray = JSON.decode(rawData) as Array;
            dataArray = new ArrayCollection(rawArray);
            arraySize = dataArray.length;
            lblStatus.text="读取成功,总共"+arraySize+"条员工信息";
        }
    
    ]]>
</mx:Script>

按钮<mx:Button id="getJson" label="读取" toolTip="读取员工数据"  x="61" y="268" width="74" height="29" click="getDataAction()"/>执行的是同样的功能。其实这时候已经完成了读取数据的工作了。要成功的运行的话,我们还需要在flex/remoting-config.xml指定channel作为flex app与java bean的沟通渠道。即添加:

 <destination id="getJsonData">
     <properties>
         <source>jsongrid.JsonGrid</source>
       </properties>
 </destination>

接下来将更新数据的功能。

首先我们要把datagrid中的data provider中的数据,这里是我们前面说的dataArray,转换成json格式,然后作为参数由remoteObject的方式传给java bean,由java bean完成跟新数据的操作。为了确保用户在更新datagrid之后能够与dataArray的数据信息保持同步,我们还需要做绑定的工作:

<mx:Binding source="dgData.dataProvider as ArrayCollection" destination="dataArray"/>

在更新之前,我们也有确保用户输入无误:我们只做简单的检查:用户名不能为空而且长度小于10:

private function checkName(event:DataGridEvent):void{
            var texIn:TextInput = TextInput(event.currentTarget.itemEditorInstance);
            var nameValue:String = texIn.text;
            if(nameValue ==""|| nameValue.length>10){
                event.preventDefault();
                lblStatus.text="姓名不能为空而且长度小于10";
            }
        }

这样之后,我们开始做更新的操作,还是要先定义一个remoteObject,指定destiontion:

<mx:RemoteObject id="sendData" destination="sendJsonData" showBusyCursor="true"result="updatedJsonDataResult(event)"/>

然后开始做用户安下更新按钮<mx:Button id="sendJson" x="254" y="268" label="更新" height="29" click="sendDataAction()" width="74"/>之后所做的程序操作,发送数据和返回结果:

private function sendDataAction():void{
            //var objSend:Object = new Object();
            var dataString:String = JSON.encode(dataArray.toArray());
            //dataString = escape(dataString);
            sendData.sendJsonArray(dataString);
            lblStatus.text = "请稍后...正在处理";
        }
 private function updatedJsonDataResult(event:ResultEvent):void{
            lblStatus.text = String(event.result as String);
        }

发送数据是以json编码再换成string格式传到后台,再有后台解码找到对应的id和name做更新操作。操作的结果会显示在lblStatus这个Label上。同样若要正确的执行程序还需要指定channel,即为flex app中的sendDataAction调用后台的sendJsonArray()方法提供沟通渠道:记载remoting-config.xml添加:

 <destination id="sendJsonData">
     <properties>
         <source>jsongrid.JsonGrid</source>
       </properties>
 </destination>

所以你前台的flex app代码应该类似如下:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Style>
    Panel {
        fontSize:16;
        fontFamily: Times New Roman;
    }
    Button {
        fontSize:16;
        color: blue;
        fontFamily: Times New Roman;
    }
    DataGrid {
        fontSize:16;
        color:green;
        fontFamily: Times New Roman;
    }
</mx:Style>
<mx:Script>
    <![CDATA[
        import mx.events.DataGridEvent;
        import mx.controls.TextInput;
        import mx.rpc.events.ResultEvent;
        import mx.collections.ArrayCollection;
        import com.adobe.serialization.json.JSON;
        
        [Bindable]
        private var dataArray:ArrayCollection;
        
        private function initDataGrid():void{
            dataArray = new ArrayCollection();
     getData.getOperation('getJsonArray').send();
        }
        
        private function getDataAction():void{
            getData.getJsonArray();
            lblStatus.text="正在读取...请稍候";
        }
        private function getJsonData(event:ResultEvent):void{
            var rawArray:Array;
            var arraySize:int;
            var rawData:String = event.result as String;
            rawArray = JSON.decode(rawData) as Array;
            dataArray = new ArrayCollection(rawArray);
            arraySize = dataArray.length;
            lblStatus.text="读取成功,总共"+arraySize+"条员工信息";
        }
        private function checkName(event:DataGridEvent):void{
            var texIn:TextInput = TextInput(event.currentTarget.itemEditorInstance);
            var nameValue:String = texIn.text;
            if(nameValue ==""|| nameValue.length>10){
                event.preventDefault();
                lblStatus.text="姓名不能为空而且长度小于10";
            }
        }
        private function sendDataAction():void{
            //var objSend:Object = new Object();
            var dataString:String = JSON.encode(dataArray.toArray());
            //dataString = escape(dataString);
            sendData.sendJsonArray(dataString);
            lblStatus.text = "请稍后...正在处理";
        }
        private function updatedJsonDataResult(event:ResultEvent):void{
            lblStatus.text = String(event.result as String);
        }
    ]]>
</mx:Script>
    <mx:RemoteObject id="sendData" destination="sendJsonData" showBusyCursor="true"result="updatedJsonDataResult(event)"/>
    <mx:RemoteObject id="getData" destination="getJsonData" source="jsongrid.JsonGrid" showBusyCursor="true"result="getJsonData(event)">
     <mx:method name="getJsonArray" result="getJsonData(event)"/>
    </mx:RemoteObject>
    <mx:Binding source="dgData.dataProvider as ArrayCollection" destination="dataArray"/>
    <mx:Panel title="员工信息管理" x="61" y="41" width="476" height="385" layout="absolute">
        <mx:DataGrid id="dgData" toolTip="姓名可编辑" x="10" y="10" width="436" height="250" dataProvider="{dataArray}"
             creationComplete="{initDataGrid()}" editable="true" itemEditEnd="{checkName(event)}"verticalScrollPolicy="on">
            <mx:columns>
                <mx:DataGridColumn headerText="编号" dataField="id" editable="false"/>
                <mx:DataGridColumn headerText="姓名*" dataField="name" editable="true"/>
                <mx:DataGridColumn headerText="性别" dataField="gender" editable="false"/>
                <mx:DataGridColumn headerText="部门" dataField="department" editable="false"/>
            </mx:columns>
        </mx:DataGrid>
        <mx:Label id="lblStatus" x="27" y="305" width="372" height="25" fontFamily="Times New Roman"fontSize="13" color="#BF03FD"/>
        <mx:Button id="getJson" label="读取" toolTip="读取员工数据" x="61" y="268" width="74" height="29"click="getDataAction()"/>
        <mx:Button id="sendJson" x="254" y="268" label="更新" height="29" click="sendDataAction()"width="74"/>
    </mx:Panel>
</mx:Application>

这个程序到此就讲解结束了,基本实现了flex app利用balzeds,java,json完成和后台的mysql的沟通:数据的读取和更新。缺点在与每次更新的时候,传递都是整个data provider中的数据,无论有的row没有被更新,都会被传递到后台做更新处理,浪费了资源。当然我们可以做到只传递更新部分的数据!!

 

这篇关于JSON扫盲帖的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/866875

相关文章

php中json_decode()和json_encode()

1.json_decode() json_decode (PHP 5 >= 5.2.0, PECL json >= 1.2.0) json_decode — 对 JSON 格式的字符串进行编码 说明 mixed json_decode ( string $json [, bool $assoc ] ) 接受一个 JSON 格式的字符串并且把它转换为 PHP 变量 参数 json

struts2中的json返回指定的多个参数

要返回指定的多个参数,就必须在struts.xml中的配置如下: <action name="goodsType_*" class="goodsTypeAction" method="{1}"> <!-- 查询商品类别信息==分页 --> <result type="json" name="goodsType_findPgae"> <!--在这一行进行指定,其中lis是一个List集合,但

特殊JSON解析

一般的与后台交互;都会涉及到接口数据的获取;而这里的数据一般情况就是JSON 了;JSON 解析起来方便;而且数据量也较小一些;所以JSON在接口数据返回中是个很不错的选择。 下面简单说下JSON解析过程中的一些案例: 这里我用到了三方的架包:fastjson-1.1.39.jar 架包 可以在我的博客中找到下载;或者网上找下 很多的; 这里主要就是映射  关系了;这就要求:实体类的名称和

用ajax json给后台action传数据要注意的问题

必须要有get和set方法   1 action中定义bean变量,注意写get和set方法 2 js中写ajax方法,传json类型数据 3 配置action在struts2中

go json反序列化成指定类型

简介 简单的介绍一下使用go的json库,将json字符串反序列化成接口中指定的实现类 代码如下 package usejsontype ExamInterface interface {CheckRule(data any) bool}type IntStru struct {DefalutVal int `json:"defalut_val"`Max int `json:

Java构造和解析Json数据的两种方法(json-lib构造和解析Json数据, org.json构造和解析Json数据)

在www.json.org上公布了很多JAVA下的json构造和解析工具,其中org.json和json-lib比较简单,两者使用上差不多但还是有些区别。下面首先介绍用json-lib构造和解析Json数据的方法示例。 一、介绍       JSON-lib包是一个beans,collections,maps,java arrays 和XML和JSON互相转换的包,主要就是用来解析Json

Ajax中根据json数据不同,对页面上的单选框Radio进行回显

Ajax中根据json数据不同,对页面上的单选框Radio进行回显 js代码: $(document).ready(function(){$.ajax({type: "POST",url: path+"/pop/nowTodayMeet2",dataType: "json",success: function(data){$("#discussTopicsEdit").val(da

C++利用jsoncpp库实现写入和读取json文件(含中文处理)

C++利用jsoncpp库实现写入和读取json文件 1 jsoncpp常用类1.1 Json::Value1.2 Json::Reader1.3 Json::Writer 2 json文件3 写json文件3.1 linux存储结果3.2 windows存储结果 3 读json文件4 读json字符串参考文章 在C++中使用跨平台的开源库JsonCpp,实现json的序列化和反序列

【SpringMVC学习07】SpringMVC与前台的json数据交互

json数据格式在接口调用中、html页面中比较常用,json格式比较简单,解析也比较方便,所以使用很普遍。在springmvc中,也支持对json数据的解析和转换,这篇文章主要总结一下springmvc中如何和前台交互json数据。 1. 两种交互形式  springmvc和前台交互主要有两种形式,如下图所示: 可以看出,前台传过来的方式有两种,一种是传json格式的数据过来,另一种

关于JSON的一些总结

一、关于JSON Json是一种类似于XML的通用数据交换格式,具有比XML更高的传输效率. 从结构上看,所有的数据(data)最终都可以分解成三种类型:  第一种类型是标量(scalar),也就是一个单独的字符串(string)或数字(numbers),比如"北京"这个单独的词。  第二种类型是序列(sequence),也就是若干个相关的数据按照一定顺序并列在一起,又叫做数组(array)或列