XML与JSON

XML语法格式

1、在文档的最开头需要先进行文档声明


2、标记

XML文档是由一个一个的标记组成的
例如:姓名

解析本地XML文件案例

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

/**
 * @ Since :  1.0
 * @ Author:  DAJ
 * @ Date  :  14:30 2021/4/18
 */
public class Demo01 {
    public static void main(String[] args) throws IOException, DocumentException {
        //1.获取输入流
        FileInputStream fis = new FileInputStream("e://hh/demo01.xml");
        //2.创建XML读取对象
        SAXReader sr = new SAXReader();
        //3.读取并得到文档对象
        Document doc = sr.read(fis);
        //4.通过文档获取根元素
        Element root = doc.getRootElement();
        //5.开始解析元素
        System.out.println(root.getName());
        //操作一波
        /*Element book = root.element("book");//book里面存的是子节点
        Element name = book.element("name");//查询子节点里面所储存的name
        System.out.println(name.getText());//射雕英雄传
        */
         List es= root.elements();
        for (int i = 0; i < es.size(); i++) {
            Element book = es.get(i);
            System.out.println(book.attributeValue("id"));
            System.out.println(book.elementText("name"));
            System.out.println(book.elementText("info"));
            System.out.println("-------------------");
        }
        /*
            books
            1
            射雕英雄传
            纯属瞎扯蛋
            -------------------
            2
            倚天屠龙记
            纯属瞎扯蛋
            -------------------
         */
        fis.close();
    }
}

解析网络XML文件案例

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * @ Since :  1.0
 * @ Author:  DAJ
 * @ Date  :  14:30 2021/4/18
 */
public class Demo02 {
    public static void main(String[] args) throws IOException, DocumentException {
        String phone = "XXXXXXXXXXXXX";//输入自己的手机号进行测试
        //  1.获取到XML资源的输入流
        URL url = new URL("http://apis.juhe.cn/mobile/get?phone=" + phone + "&dtype=xml&key=9f3923e8f87f1ea50ed4ec8c39cc9253");
        //建立连接
        URLConnection conn = url.openConnection();
        InputStream is = conn.getInputStream();
        //2. 创建一个XML读取对象
        SAXReader sr = new SAXReader();
        //3. 通过读取对象 读取XML数据,并返回文档对象
        Document doc = sr.read(is);
        //4.获取根节点
        Element root = doc.getRootElement();
        //5. 解析内容
        String code = root.elementText("resultcode");
        if ("200".equals(code)) {
            //如果root根节点下的resultcode子节点为200,说明号码正确,在查询result子节点里面的内容
            Element result = root.element("result");
            String province = result.elementText("province");
            String city = result.elementText("city");
            if (province.equals(city)) {
                System.out.println("手机号码归属地为:" + city);
            } else {
                System.out.println("手机号码归属地为:" + province + " " + city);
            }
        } else {
            System.out.println("请输入正确的手机号码");
        }

    }
}

JSON

JSON: JavaScript Object Notation JS对象简谱 , 是一种轻量级的数据交换格式.

对象格式

js:
	var b = new Object();
	b.name = "金苹果";
	b.info = "种苹果";
XML:
	
		金苹果
		种苹果
	
JSON:
	{
		"name":"金苹果",
		"info":"种苹果"
	}
	

数组格式

在JSON格式中可以与对象互相嵌套
[元素1,元素2...]

{
			"name":"孙悟空",
			"age":18,
			"pengyou":["张三","李四","王二","麻子",{
							"name":"唐僧",
							"info":"像匹野马一样狂奔在技术钻研的道路上"
			}],
			"heihei":{
			"name":"大长刀",
			"length":"40m"
			}
}

JSON的作用

将Java中的对象 快速的转换为 JSON格式的字符串.
将JSON格式的字符串, 转换为Java的对象.

Gson

将对象转为JSON字符串

import com.google.gson.Gson;

/**
 * @ Since :  1.0
 * @ Author:  DAJ
 * @ Date  :  20:13 2021/4/18
 */
public class Demo01 {
    public static void main(String[] args) {
        //1.    创建Gson对象
        Gson g = new Gson();
        //2.    转换
        Book b = new Book("100","java入门","java新手入门介绍");
        //将book转换为字符串
        String s = g.toJson(b);
        System.out.println(s);//{"id":"100","name":"java入门","info":"java新手入门介绍"}

    }
}

将JSON字符串转换为对象

import com.google.gson.Gson;

/**
 * @ Since :  1.0
 * @ Author:  DAJ
 * @ Date  :  20:13 2021/4/18
 */
public class Demo02 {
    public static void main(String[] args) {
        //1.    创建Gson对象
        Gson g = new Gson();
        //2.    转换 {"id":"100","name":"java入门","info":"java新手入门介绍"}
        Book b = g.fromJson("{\"id\":\"100\",\"name\":\"java入门\",\"info\":\"java新手入门介绍\"}", Book.class);
        System.out.println(b);//Book{id='100', name='java入门', info='java新手入门介绍'}

    }
}

FastJson

将对象转换为JSON字符串

/**
 * @ Since :  1.0
 * @ Author:  DAJ
 * @ Date  :  21:06 2021/4/18
 */
public class Demo04 {
    public static void main(String[] args) {
        //使用阿里云fastJSON,把对象转成JSON字符串
        Book book = new Book("1", "java入门", "适合刚学习java 的同学");
        //1.转换
        String json = JSON.toJSONString(book);
        System.out.println(json);//{"id":"1","info":"适合刚学习java 的同学","name":"java入门"}
    }
}

将JSON字符串转换为对象

/**
 * @ Since :  1.0
 * @ Author:  DAJ
 * @ Date  :  21:28 2021/4/18
 */
public class Demo05 {
    public static void main(String[] args) {
        //  1.转换 :{"id":"1","info":"适合刚学习java 的同学","name":"java入门"}
        //将json解析成对象
        Book book = JSON.parseObject("{\"id\":\"1\",\"info\":\"适合刚学习java 的同学\",\"name\":\"java入门\"}", Book.class);
        System.out.println(book.getId());//1


    }
}

你可能感兴趣的:(XML与JSON)