jaxa技术2

XStream

1. 什么作用
  * 可以把JavaBean转换为(序列化为)xml

2. XStream的jar包
  * 核心JAR包:xstream-1.4.7.jar;
  * 必须依赖包:xpp3_min-1.1.4c(XML Pull Parser,一款速度很快的XML解析器);

3. 使用步骤
  * XStream xstream = new XStream();
  * String xmlStr = xstream.toXML(javabean);

4. 使用细节
  * 别名:把类型对应的元素名修改了
    > xstream.alias("china", List.class):让List类型生成的元素名为china
    > xstream.alias("province", Province.class):让Province类型生成的元素名为province
  * 使用为属性:默认类的成员,生成的是元素的子元素!我们希望让类的成员生成元素的属性
    > xstream.useAttributeFor(Province.class, "name"):把Province类的名为name成员,生成<province>元素的name属性
  * 去除Collection类型的成名:我们只需要Collection的内容,而不希望Collection本身也生成一个元素
    > xstream.addImplicitCollection(Province.class, "cities"):让Province类的名为cities(它是List类型的,它的内容还会生成元素)的成名不生成元素
  * 去除类的指定成名,让其不生成xml元素
    > xstream.omitField(City.class, "description"):在生成的xml中不会出现City类的名为description的对应的元素!
代码:

 

public List<Province> getProvinceList(){
       Province p1=new Province();
       p1.setName("北京");
       p1.addCity(new  City("昌平区","changpingqu"));
       p1.addCity(new  City("东城区","dongchengqu"));
       Province p2=new Province();
       p2.setName("河南");
       p2.addCity(new  City("郑州","zhengzhou"));
       p2.addCity(new  City("洛阳","luoyang"));
       List<Province> list=new  ArrayList<Province>();
       list.add(p1);
       list.add(p2);
      
       return list;
       
   }
   @Test
   public void fun(){
       List<Province> prList = getProvinceList();
       XStream  xstream=new XStream();
       xstream.alias("china", List.class);//修改别名给List指定为china
       xstream.alias("Province",Province.class);
       xstream.alias("City", City.class);
       //把<name>北京</name>属性改成<Province>属性
       xstream.useAttributeFor(Province.class,"name");
     //移除cities标签
       xstream.addImplicitCollection(Province.class, "cities");
       //移除 <description></description>标签
       xstream.omitField(City.class,"description" );
       String s=xstream.toXML(prList);//
       System.out.println(s); 
   }
}

 

 


====================================================================================


JSON

1. json是什么
  * 它是js提供的一种数据交换格式!

2. json的语法
  * {}:是对象!
    > 属性名必须使用双引号括起来!单引不行!!!
    > 属性值:
      * null
      * 数值
      * 字符串
      * 数组:使用[]括起来
      * boolean值:true和false

3. 应用json
  * var person = {"name":"zhangSan", "age":18, "sex":"male"};

4. json与xml比较
* 可读性:XML胜出
* 解析难度:JSON本身就是JS对象(主场作战),所以简单很多
* 流行度:XML已经流行好多年,但在AJAX领域,JSON更受欢迎。

-----------------------------------

json-lib

1. 是什么?
  * 它可以把javabean转换成json串
2. 核心类
  * JSONObject --> Map
    > toString();
    > JSONObject map = JSONObject.fromObject(person):把对象转换成JSONObject对象
  * JSONArray --> List
    > toString()
    > JSONArray jsonArray = JSONObject.fromObject(list):把list转换成JSONArray对象

posted @ 2017-04-14 17:40  晓梦蝶  阅读(254)  评论(0编辑  收藏  举报