您现在的位置是: 首页

XML & JSON

程序员文章站 2022-07-15 10:45:08
...

XML

可扩展标记语言

XML & JSON

显示数据是HTML做的事情,而XML就是数据+含义,是用来传输数据的

XML & JSON

XML里面的标签是自己定义的,想怎么定义就怎么定义

XML本质是就是一个文本文件

XML & JSON

      XML 文档形成一种树结构,XML 文档必须包含根元素。该元素是所有其他元素的父元素。XML 文档中的元素形成了一棵文档树。这棵树从根部开始,并扩展到树的最底端。

XML & JSON

XML & JSON

XML & JSON

XML & JSONXML & JSON

XML解析——DOM方法

XML & JSONXML & JSONXML & JSON

 

 

JSON

XML & JSON

 

在JSON中:

  • 对象表示为键值对
  • 数据由逗号分隔
  • 花括号保存对象
  • 方括号保存数组

XML & JSON

 

 

Java的JSON处理

KV对

XML & JSON

java本身没有JSON的处理工具,不像XML,JAVA内置了解析办法。JSON要依赖于第三方包来进行处理

org.json



import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 采用org.json包来解析JSON
 * @author Tom
 *
 */

public class OrgJsonTest {
	public static void main(String[] args) {
		testJsonObject();
		System.out.println("=========华丽丽的分割线==============");
		testJsonFile();
	}
    public static void testJsonObject() {
    	//构造对象
    	Person p = new Person();
    	p.setName("Tom");
    	p.setAge(20);
    	p.setScores(Arrays.asList(60,70,80));
    	
    	
    	//构造JSONObject对象
    	JSONObject obj = new JSONObject(); 	
    	
        //string
    	obj.put("name", p.getName());
        //int
    	obj.put("age", p.getAge());
        //array
        obj.put("scores", p.getScores());
        //null
        //object.put("null", null);
        System.out.println(obj);        
        
        System.out.println("name: " + obj.getString("name"));
        System.out.println("age: " + obj.getInt("age"));
        System.out.println("scores: " + obj.getJSONArray("scores"));
    }

    public static void testJsonFile() {
    	File file = new File("books.json");
        try (FileReader reader = new FileReader(file)) {
        	//读取文件内容到JsonObject对象中
            int fileLen = (int) file.length(); 
            char[] chars = new char[fileLen];
            reader.read(chars);
            String s = String.valueOf(chars);
            JSONObject jsonObject = new JSONObject(s);
            
            //开始解析JSONObject对象
            JSONArray books = jsonObject.getJSONArray("books");
            List<Book> bookList = new ArrayList<>();
            for (Object book : books) {
            	//获取单个JSONObject对象
                JSONObject bookObject = (JSONObject) book;
                Book book1 = new Book();
                book1.setAuthor(bookObject.getString("author"));
                book1.setYear(bookObject.getString("year"));
                book1.setTitle(bookObject.getString("title"));
                book1.setPrice(bookObject.getInt("price"));
                book1.setCategory(bookObject.getString("category"));
                bookList.add(book1);
            }
            
            for(Book book:bookList)
            {
            	System.out.println(book.getAuthor() + ",  " + book.getTitle());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

books.json的格式

XML & JSON

XML & JSON

GSON

import java.io.File;
import java.io.FileReader;
import java.util.Arrays;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

/**
 * 采用Google GSON来处理JSON
 * @author Tom
 *
 */
public class GsonTest {
	public static void main(String[] args) {
		testJsonObject();
		System.out.println("=========华丽的分割线==============");
		testJsonFile();
	}
	public static void testJsonObject() {
		//构造对象
    	Person p = new Person();
    	p.setName("Tom");
    	p.setAge(20);
    	p.setScores(Arrays.asList(60,70,80));
		
    	//从Java对象到JSON字符串
		Gson gson = new Gson();
		String s = gson.toJson(p);
		System.out.println(s); //{"name":"Tom","age":20,"scores":[60,70,80]}
		
		//从JSON字符串到Java对象
		Person p2 = gson.fromJson(s, Person.class);
		System.out.println(p2.getName());  //Tom
		System.out.println(p2.getAge());   //20
		System.out.println(p2.getScores());//[60, 70, 80]
		
		//调用GSON的JsonObject
		JsonObject json = gson.toJsonTree(p).getAsJsonObject(); //将整个json解析为一颗树
		System.out.println(json.get("name"));  //"Tom"
		System.out.println(json.get("age"));   //20
		System.out.println(json.get("scores"));//[60,70,80]
		
	}
	
	public static void testJsonFile() {
		Gson gson = new Gson();
		File file = new File("books2.json");
		
        try (FileReader reader = new FileReader(file)) {
        	List<Book> books = gson.fromJson(reader, new TypeToken<List<Book>>(){}.getType());
            
        	for(Book book : books)
        	{
        		System.out.println(book.getAuthor() + ",  " + book.getTitle());
        	}
        } catch (Exception e) {
            e.printStackTrace();
        }
	}
}

XML & JSON

Jackson


	import java.io.File;
	import java.io.IOException;
	import java.util.ArrayList;
	import java.util.Arrays;
	import java.util.HashMap;
	import java.util.List;
	import java.util.Map;

	import com.fasterxml.jackson.core.JsonProcessingException;
	import com.fasterxml.jackson.core.type.TypeReference;
	import com.fasterxml.jackson.databind.JsonNode;
	import com.fasterxml.jackson.databind.ObjectMapper;
	import com.google.gson.reflect.TypeToken;

	/**
	 * 采用Jackson来处理JSON
	 * @author Tom
	 *
	 */

	public class JacksonTest {

		public static void main(String[] args) throws Exception {
			testJsonObject();
			System.out.println("=========华丽丽的分割线==============");
			testJsonFile();
		}
		
		static void testJsonObject() throws IOException {
			ObjectMapper om = new ObjectMapper();
			
			//构造对象
	    	Person p = new Person();
	    	p.setName("Tom");
	    	p.setAge(20);
	    	p.setScores(Arrays.asList(60,70,80));
	    	
	    	//将对象解析为json字符串
			String jsonStr = om.writeValueAsString(p);
			System.out.println(jsonStr);
			
			//从json字符串重构对象
			Person p2 = om.readValue(jsonStr, Person.class);
			System.out.println(p2.getName());
			System.out.println(p2.getAge());
			System.out.println(p2.getScores());
			
			//从json字符串重构为JsonNode对象
			JsonNode node = om.readTree(jsonStr);
			System.out.println(node.get("name").asText());
			System.out.println(node.get("age").asText());
			System.out.println(node.get("scores"));		
		}
		
		static void testJsonFile() throws IOException {
			ObjectMapper om = new ObjectMapper();
			
			//从json文件中加载,并重构为java对象
			File json2 = new File("books2.json");
			List<Book> books = om.readValue(json2, new TypeReference<List<Book>>(){});
			for (Book book : books) {
				System.out.println(book.getAuthor());
				System.out.println(book.getTitle());
			}
		}	
	}


 

相关标签: XML JSON