json&xml學習筆記--Java讀取本地json文件

寫在前面

嗯,以前沒具體學習過JSON相關知識,最近整理文檔,順便作個總結。java

本篇文章實現了Java讀取本地json文件功能——使用commons.io和fastjson實現。apache

所需jar包:

commons-io-2.6.jar;json

fastjson-1.2.28.jar;數組

json文件:

books.xml,位於src根目錄下:學習

{
  "message": "這是一箇中文測試",
  "info": {
    "fileType": "json",
    "fileUsage": "我在哪裏?我要作什麼?"
  },
  "books": [{
    "title": "Everyday Italian",
    "author": "Giada De Laurentiis",
    "year": "2005",
    "price": 30.00
  	},
    {
      "title": "Harry Potter",
      "author": "J K. Rowling",
      "year": "2005",
      "price": 29.99
    },
    {
      "title": "Learning JSON",
      "author": "Erik T. Ray",
      "year": "2005",
      "price": 39.95
    }
  ]
}

Java代碼:

package books;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class GetJson {

	public static void main(String[] args) {
		try {
//			獲取JSON文件內容,轉化爲字符串類型
			String jsonStr = FileUtils.readFileToString(new File("src/books.json"), "UTF-8");
//			將字符串轉化爲json
			JSONObject jsonObject = JSON.parseObject(jsonStr);

//			獲取單個屬性值
			String message = (String) jsonObject.get("message");
			System.out.println("***message***");
			System.out.println("message= " + message);
			
//			獲取對象值
			JSONObject info = jsonObject.getJSONObject("info");
			String fileType = info.getString("fileType");
			String fileUsage = info.getString("fileUsage");
			System.out.println("***info***");
			System.out.println("    fileType=" + fileType);
			System.out.println("    fileUsage=" + fileUsage);
			
//			獲取數組值
			JSONArray jsonArray = jsonObject.getJSONArray("books");
			System.out.println("***books***");

			for(int i = 0; i < jsonArray.size(); i++) {
				System.out.println("***book***");
				JSONObject jObject = (JSONObject) jsonArray.get(i);
				String title = jObject.getString("title");
				String author = jObject.getString("author");
				String year = jObject.getString("year");
				double price = jObject.getDoubleValue("price");
				
				System.out.println("    title=" + title);
				System.out.println("    author=" + author);
				System.out.println("    year=" + year);
				System.out.println("    price=" + price);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

輸出結果:

***message***
message= 這是一箇中文測試
***info***
    fileType=json
    fileUsage=我在哪裏?我要作什麼?
***books***
***book***
    title=Everyday Italian
    author=Giada De Laurentiis
    year=2005
    price=30.00
***book***
    title=Harry Potter
    author=J K. Rowling
    year=2005
    price=29.99
***book***
    title=Learning JSON
    author=Erik T. Ray
    year=2005
    price=39.95
相關文章
相關標籤/搜索