java高级工程师-----JSON和XML的使用

来源:互联网 发布:sql截掉字符串 编辑:程序博客网 时间:2024/06/01 16:04
  • JSON和XML的比较

编码的可读性,xml有明显的优势,毕竟人类的语言更贴近这样的说明结构。json读起来更像一个数据块,读起来就比较费解了。不过,我们读起来费解的语言,恰恰是适合机器阅读,所以通过json的索引.province[0].name就能够读取“黑龙江”这个值。
编码的手写难度来说,xml还是舒服一些,好读当然就好写。不过写出来的字符JSON就明显少很多。去掉空白制表以及换行的话,JSON就是密密麻麻的有用数据,而xml却包含很多重复的标记字符。

  • JSON的理解

JSON建构有两种结构[1]
json简单说就是javascript中的对象和数组,所以这两种结构就是对象和数组2种结构,通过这两种结构可以表示各种复杂的结构
1、对象:对象在js中表示为“{}”扩起来的内容,数据结构为 {key:value,key:value,...}的键值对的结构,在面向对象的语言中,key为对象的属性,value为对应的属性值,所以很容易理解,取值方法为 对象.key 获取属性值,这个属性值的类型可以是 数字、字符串、数组、对象几种。
2、数组:数组在js中是中括号“[]”扩起来的内容,数据结构为 ["java","javascript","vb",...],取值方式和所有语言中一样,使用索引获取,字段值的类型可以是 数字、字符串、数组、对象几种。

  • JSON的基本使用

1)//转换成为JSONObject对象 JSONObject jsonObj = new JSONObject(jsonStr);2)//json转换为字符串数据
public static void main(String[] args) throws JSONException {
         
         //创建JSONObject对象
         JSONObject json = new JSONObject();
         
         //向json中添加数据
         json.put("username", "wanglihong");
         json.put("height", 12.5);
         json.put("age", 24);
         
         //创建JSONArray数组,并将json添加到数组
         JSONArray array = new JSONArray();
         array.put(json);
         
         //转换为字符串
         String jsonStr = array.toString();
         
         System.out.println(jsonStr);
     }

3)对集合的转换

public static void main(String[] args)throws JSONException{
         //初始化ArrayList集合并添加数据
         List<String> list = new ArrayList<String>();
         list.add("username");
         list.add("age");
         list.add("sex");
         
         //初始化HashMap集合并添加数组
         Map map = new HashMap();
         map.put("bookname", "CSS3实战");
         map.put("price", 69.0);
         
         //初始化JSONArray对象,并添加数据
         JSONArray array = new JSONArray();
         array.put(list);
         array.put(map);
         
         //生成的JSON字符串为:[["username","age","sex"],{"price":69,"bookname":"CSS3实战"}]
     }

  • XML的理解
  • XML的作用区域
  • XML的基本使用

解析xml的API  :DOM(文档对象模型,核心是节点,可以上下导航,数据保存在内存中)  -------------------用得比较多

                      SAX(顺序读取文件,不能上下读取,事件驱动,用得比较少)

通过w3c的包DOM解析xml的代码:

import org.w3c.dom.Document

public class DomHandler{

    public  void read(String   fileName) throws  Exception{

   DocumentBuliderFactory   factory = DocumentBuilderFactory.newInstance();

  DocumentBuilder builder=factory.newDocumentBuilder();

Document document = builder.parse(this.getClass().getResourceAsStream("/"+fileName));//到这一步整个xml内容已经被保存在内存中了

//读取根节点

Element  root=document.getDocumentElement();

//获取指定节点的所有所有节点

NodeList  nodeList=root.getElementsByTagName("database");

for(int i=0;i<nodeList.getLength();i++){

Node  node=nodeList.item(i);

NameNodeMap   attributes  = node.getAttributes();

for(int j=0;j<attributes.getLength();j++){

Node  attribute= attributes.item(j);

}

}

}

}

通过DOM4j来解析xml:

public class  Dom4jHander{

  public  void  read(String  fileName)  throws  Exception{

SAXReader   saxReader=new  SAXReader();

Document document=saxReader.read(this.getClass().getResourceAsStream("/"+fileName);

Element  root= document.getRootElement();

List<Element>  childElements = root.elements("database");

for(Element  child:childElements){

//获取属性  不知道属性名称是的遍历方法

List<Attribute>  attributes=child.attributes();

for(Attribute  attribute:attributes){

//attribute.getName()  和attribute.getValue();

}

//获取已知属性的值

String    name=child.attributeValue("name");

}

}

//添加xml内容 

public  void  add()  throws  Exception{

//创建xml文档

Document docment=DocumentHelper.createDocment();

//添加根节点

Element root = document.addElement("dataSource");

//节点下添加子节点

Element   database=root.addElement("database");

//3.将document写出到文件

OutputFormat of= OutputFormat.createPrettyPrint();

of.setEncoding("GBK");

XMLWriter  xw=new  XMLWriter(new  FileOutputStream("db.xml"),of);

xw.write(document);


}


}




原创粉丝点击