JSON

clarancepeng

字号+ 作者:H5之家 来源:H5之家 2018-01-21 18:07 我要评论( )

JSON作为一种信息的载体伴随着AJAX的红火也越来越得到广大用户的青睐和认可!在没有使用JSON的时候,数据 从后台数据库到前台AJAX的返回显示,一般都 ...

JSON技术实战 博客分类:

  • 程中淘沙
  •  

    JSON作为一种信息的载体伴随着AJAX的红火也越来越得到广大用户的青睐和认可!在没有使用JSON的时候,数据
    从后台数据库到前台AJAX的返回显示,一般都要经过SQL查询--数据封装(封装成字符串或者XML文本)--前台解析
    字符串或者XML文本,提取需要的东西出来。这其中包含了太多的转换关系,劳明伤财,也有很多人在探索一种
    能够使大家都能认识的数据结构,这个时候大家都想到了JSON,可以说JSON也不是新的东西,出来好多年了,
    Javascript一直都内置了JSON的支持,很多时候我们都是使用JSON的语法来定义一个Javascript的对象!看一看
    JSON的官方网站()就知道它目前基本上已经覆盖了大多数语言,这意味着大多数情况下的跨语言
    环境下的数据交换,使用JSON是一个不错的选择!
    1. Javascript(虽然已经内置支持,但是这里有一个开发包可以使用)
      (1) 使用JSON语法定义一个Javascript对象
      var myJSONObject = {"bindings": [
            {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^*"},
            {"ircEvent": "PRIVMSG", "method": "deleteURI", "regex": "^delete.*"},
            {"ircEvent": "PRIVMSG", "method": "randomURI", "regex": "^random.*"}
        ]
      };
      myJSONObject.bindings[0].method 将返回newURI
      (2) 把普通字符串转换成JavaScript对象(需要扩展包支持)
      var myObject = JSON.parse(myJSONtext, filter);
      myData = JSON.parse(text, function (key, value) { return key.indexOf('date') >= 0 ? new Date(value) : value;    });
      (3) JSON对象转换成字符串
      var myJSONText = JSON.stringify(myObject);

    2. Java对JSON的支持(没有原生的支持,需要使用第三方的扩展包来实现)
       Java的JSON开发包很多,也有很多实用且功能强大的
       (1) json-lib ()
       a.) JSON和Java的类型对应关系
    JSON  Java
    string <=> java.lang.String, java.lang.Character, char
    number <=> java.lang.Number, byte, short, int, long, float, double
    true|false <=> java.lang.Boolean, boolean
    null <=> null
    function <=> net.sf.json.JSONFunction
    array <=> net.sf.json.JSONArray (object, string, number, boolean, function)
    object <=> net.sf.json.JSONObject
    b.) json-lib的依赖库
    jakarta commons-lang 2.3
    jakarta commons-beanutils 1.7.0
    jakarta commons-collections 3.2
    jakarta commons-logging 1.1
    ezmorph 1.0.3
    xom 1.1(如果要用到xml文件的解析的话)
      c.) 可运行实例
    package com.gomt.json.jsonlib;

    import java.lang.reflect.InvocationTargetException;
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;

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

    import org.apache.commons.beanutils.PropertyUtils;

    public class JsonLibMain {

    public JsonLibMain() {
    // TODO Auto-generated constructor stub
    }

    /**
    * @param args
    * @throws NoSuchMethodException
    * @throws InvocationTargetException
    * @throws IllegalAccessException
    */
    public static void main(String[] args) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    boolean[] boolArray = new boolean[]{true,false,true};  
    JSONArray jsonArray = JSONArray.fromObject( boolArray );  
    System.out.println("***1*** = " + jsonArray );

    Collection<String> list = new ArrayList<String>();  
    list.add( "first" );  
    list.add( "second" );  
    jsonArray = JSONArray.fromObject( list );  
    System.out.println("***2*** = " + jsonArray );

    jsonArray = JSONArray.fromObject( "['json','is','easy']" );  
    System.out.println("***3*** = " + jsonArray );

    Map<String, Object> map = new HashMap<String, Object>();  
    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 jsonObject = JSONObject.fromObject( map );  
    System.out.println("***4*** = " + jsonObject );

    jsonObject = JSONObject.fromObject( new MyBean() );  
    System.out.println("***5*** = " +  jsonObject );

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

    jsonObject = JSONObject.fromObject( json );  
    Object bean = JSONObject.toBean( jsonObject );  
    System.out.print("***6*** = " +  jsonObject.get( "name" ) + " " + PropertyUtils.getProperty( bean, "name" ) );  
    System.out.print("\t " +  jsonObject.get( "bool" ) + " = " + PropertyUtils.getProperty( bean, "bool" ) );  
    System.out.print("\t " +  jsonObject.get( "int" ) + " = " + PropertyUtils.getProperty( bean, "int" ) );  
    System.out.print("\t " +  jsonObject.get( "double" ) + " = " + PropertyUtils.getProperty( bean, "double" ) );  
    System.out.print("\t " +  jsonObject.get( "func" ) + " = " + PropertyUtils.getProperty( bean, "func" ) );  
    List expected = JSONArray.toList( jsonObject.getJSONArray( "array" ) );  
    System.out.println("\t " +  expected + " = " + (List) PropertyUtils.getProperty( bean, "array" ) );

    json = "{bool:true,integer:1,string:\"json\"}";  
    jsonObject = JSONObject.fromObject( json );  
    MyBean myBean = (MyBean) JSONObject.toBean( jsonObject, MyBean.class );  
    System.out.print("***7*** = " +  jsonObject.get( "bool" ) + " = " + Boolean.valueOf( myBean.isBool() ) );  
    System.out.print("\t " +  jsonObject.get( "integer" ) + " = " +new Integer( myBean.getInteger() ) );  
    System.out.println("\t " +  jsonObject.get( "string" )+ " = " + myBean.getString() );

    //需要用到ezmorph
    json = "{'data':[{'name':'clarance','userId':100001},{'name':'peng','userId':100002}]}";  
    Map<String,Class<Person>> classMap = new HashMap<String,Class<Person>>();  
    classMap.put( "data", Person.class );
    myBean = (MyBean)JSONObject.toBean(JSONObject.fromObject(json), MyBean.class, classMap);
    if(myBean != null && myBean.getData() != null) {
    for(Person p : myBean.getData()) {
    System.out.println("***8*** = " +  "用户id: " + p.getUserId() + " 用户名: " + p.getName());
    }
    }

    /*
    Morpher dynaMorpher = new BeanMorpher( Person.class, JSONUtils.getMorpherRegistry() );  
    MorpherRegistry morpherRegistry = new MorpherRegistry();
    morpherRegistry.registerMorpher( dynaMorpher );  
    List output = new ArrayList();  
    for( Iterator i = myBean.getData().iterator(); i.hasNext(); ){  
       output.add( morpherRegistry.morph( Person.class, i.next() ) );  
    }  
    myBean.setData( output );
    */
    /**
    * XML和JSON之间的转换,需要用到xom
    */
    jsonObject = new JSONObject( true );  
    XMLSerializer xmls = new XMLSerializer();
    String xml = xmls.write( jsonObject );
    System.out.println("***9*** = " + xml);

    jsonObject = JSONObject.fromObject("{\"name\":\"json\",\"bool\":true,\"int\":1}");  
    xmls = new XMLSerializer();
    xml = xmls.write( jsonObject );
    System.out.println("***10*** = " + xml);

    jsonArray = JSONArray.fromObject("[1,2,3]");  
    xmls = new XMLSerializer();
    xml = xmls.write( jsonArray );
    System.out.println("***11*** = " + xml);

    xml = "<a class=\"array\"><e type=\"function\" params=\"i,j\">return matrix[i][j];</e></a> ";
    xmls = new XMLSerializer();
    jsonArray = (JSONArray) xmls.read( xml);
    System.out.println("***12*** = " +  jsonArray );

    }

    }

    package com.gomt.json.jsonlib;

    import java.util.List;

    import net.sf.json.JSONFunction;

    public class MyBean implements java.io.Serializable {
    private static final long serialVersionUID = -784610042144660631L;
    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];");
       private Integer integer;
       private Boolean bool;
       private String string;
       private List<Person> data;
      
    public Boolean isBool() {
    return bool;
    }
    public void setBool(Boolean bool) {
    this.bool = bool;
    }
    public String getString() {
    return string;
    }
    public void setString(String string) {
    this.string = string;
    }
    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;
    }
    public Integer getInteger() {
    return integer;
    }
    public void setInteger(Integer integer) {
    this.integer = integer;
    }
    public Boolean getBool() {
    return bool;
    }
    public List<Person> getData() {
    return data;
    }
    public void setData(List<Person> data) {
    this.data = data;
    }
         
    }
     

    package com.gomt.json.jsonlib;

    import java.io.Serializable;

    public class Person implements Serializable {

    private static final long serialVersionUID = 7699163849016962711L;
    private int userId;
    private String name;
    public int getUserId() {
    return userId;
    }
    public void setUserId(int userId) {
    this.userId = userId;
    }
    public String getName() {
    return name;
    }
    public void setName(String name) {
    this.name = name;
    }
    }

    d.) 运行结果
    ***1*** = [true,false,true]
    ***2*** = ["first","second"]
    ***3*** = ["json","is","easy"]
    ***4*** = {"func":function(i){ return this.arr[i]; },"arr":["a","b"],"int":1,"name":"json","bool":true}
    ***5*** = {"string":"","integer":0,"func1":function(i){ return this.options[i]; },"data":[],"pojoId":1,"name":"json","bool":false,"options":["a","f"],"func2":function(i){ return this.options[i]; }}
    ***6*** = json json true = true 1 = 1 2.2 = 2.2 function(a){ return a; } = function(a){ return a; } [1, 2] = [1, 2]
    ***7*** = true = true 1 = 1 json = json
    ***8*** = 用户id: 100001 用户名: clarance
    ***8*** = 用户id: 100002 用户名: peng
    ***9*** = <?xml version="1.0" encoding="UTF-8"?>
    <o null="true"/>

    ***10*** = <?xml version="1.0" encoding="UTF-8"?>
    <o><bool type="boolean">true</bool><int type="number">1</int><name type="string">json</name></o>

    ***11*** = <?xml version="1.0" encoding="UTF-8"?>
    <a><e type="number">1</e><e type="number">2</e><e type="number">3</e></a>

    2007-12-7 9:08:29 net.sf.json.xml.XMLSerializer getType
    信息: Using default type string
    ***12*** = [function(i,j){ return matrix[i][j]; }]

    分享到:

    | 使用ajaxtags实现菜单级连

     

    1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

    相关文章
    • 使用Jquery+Ajax+Json如何实现分页显示附JAVA+JQuery实现异步分

      使用Jquery+Ajax+Json如何实现分页显示附JAVA+JQuery实现异步分

      2018-01-21 18:13

    • 超越XML和JSON:YAML,Java开发人员的新选择[3]

      超越XML和JSON:YAML,Java开发人员的新选择[3]

      2018-01-21 17:00

    • java 生成json与解析

      java 生成json与解析

      2018-01-21 11:15

    • Gson入门教程,json

      Gson入门教程,json

      2018-01-21 09:06

    网友点评