JSON-5/6(保存JSON到文件 )

 注:一般来说,JSON是用于网络传输h或者存储到数据库中,很少用于保存文件

一、JSON存储到文件

无论是JSONObject,还是JSONArray ,

都可以先转成String再存储到文件。

这个过程已经封装到JsJSON.toFile()里。

package json04;

import java.io.File;

import org.json.JSONObject;

public class WriteJSON 
{
	
	public static void main(String[] args) throws Exception
	{
		    //生成JSONObject
			JSONObject j1=new JSONObject();
			j1.put("name", "郭少");
			j1.put("id", 998856);
			j1.put("sex", true);
			j1.put("phone", "15199978652");
			
			
			//写入到JSON文件
			File file=new File("student.txt");
			JsJSON.toFile(j1, file, "utf-8");
			System.out.println("exit");
		 
	}
}

二、从文件中读取内容并转成JSON

如果文件中存储的是 { ... } ,则自动转成 JSONObject

如果文件中存储的是 [ ... ] ,则自动转成 JSONArray

在JsJSON.fromFile() 里已经封装了这个逻辑,

已经能够自动读取文件中的内容、并自动转成JSONObject 或 JSONArray

package json04;

import java.io.File;

import org.json.JSONObject;

public class ReadJSON {

	public static void main(String[] args) throws Exception 
	{
		//从文件中读取内容并转成JSON
		File file=new File("student.txt");
		JSONObject j1=(JSONObject)JsJSON.fromFile(file, "utf-8");
		
		String jsonstr=j1.toString(2);   //缩进2
		System.out.println(jsonstr);
		
		System.out.println("exit");

	}

}

 

JsJSON

package json04;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

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

public class JsJSON
{
	// json: 可以是JSONObject 或 JSONArray
	// encoding: "UTF-8", "GBK"
	public static void toFile(Object json, File file, String encoding) throws Exception
	{
		String jsonstr = null;
		if(json instanceof JSONObject)
			jsonstr = ((JSONObject)json).toString(2);
		else if(json instanceof JSONArray)
			jsonstr = ((JSONArray)json).toString(2);
		else 
			throw new Exception("Must be org.json.JSONObject or org.json.JSONArray");
		
		// 存入文件
		OutputStream outputStream = new FileOutputStream(file);
		try {
			// UTF-8写入BOM头部
			encoding=encoding.toUpperCase();
			if(encoding.equals("UTF-8"))
			{
				byte[] bom = { (byte)0xEF, (byte)0xBB,(byte) 0xBF };
				outputStream.write(bom);
			}
			
			byte[] data = jsonstr.getBytes(encoding);
			outputStream.write(data);
		}finally {
			// 确保文件被关闭
			try { outputStream.close();} catch(Exception e) {}
		}
	}
	
	public static Object fromFile(File file, String encoding) throws Exception
	{		
		
		InputStream inputStream = new FileInputStream(file);
		try {
			int fileSize = (int)file.length();
			byte[] data = new byte[fileSize];
			int n = inputStream.read(data);
			
			int offset = 0;
			encoding=encoding.toUpperCase();
			if(n > 3 && encoding.equals("UTF-8"))
			{
				if(data[0] == (byte)0xEF && data[1]==(byte)0xBB && data[2] == (byte)0xBF)
					offset = 3; // 前3个字节是BOM
			}
			
			String jsonstr = new String(data, offset, n-offset, encoding);
			
			// 找第一个非空白字符, 从而判断它是JSONObject 还是JSONArray
			char firstChar = ' ';
			for(int i=0; i<jsonstr.length(); i++)
			{
				firstChar = jsonstr.charAt(i);
				if(firstChar != ' ' && firstChar != '\t' && firstChar != '\n' && firstChar != '\r')
					break;
			}
			
			// 如果以{开头,则转成JSONObject; 如果以[开头,则转成 JSONArray
			if(jsonstr.startsWith("{") )
			{
				return new JSONObject( jsonstr );
			}
			else if(jsonstr.startsWith("[") )
			{
				return new JSONArray ( jsonstr);
			}
			else
			{
				throw new Exception("JSON must begin with { or [ !");
			}
			
		}finally {
			try {inputStream.close();} catch(Exception e) {}
		}
	}
	
	//
	// 在JSONObject里已经有了现成的方法, 以opt开头的方法都是带默认值的
	// JSONObject.optInt()
	// JSONObject.optLong()
	// JSONObject.optString()
	// JSONObject.optBoolean()
	
	
	
	// ... 注 :以下方法重复,不需要了 ... 带缺省值得get方法
	// 相当于 JSONObject.optInt()
	public static int getInt (JSONObject json, String key, int defValue)
	{
		try {
			return json.getInt(key);
		}catch(Exception e)
		{
			return defValue;
		}
	}
	// 相当于 JSONObject.optLong()
	public static long getLong (JSONObject json, String key, long defValue)
	{
		try {
			return json.getLong(key);
		}catch(Exception e)
		{
			return defValue;
		}
	}

	// 相当于 JSONObject.optString()
	public static String getString (JSONObject json, String key, String defValue)
	{
		try {
			return json.getString(key);
		}catch(Exception e)
		{
			return defValue;
		}
	}
	// 相当于 JSONObject.optBoolean()
	public static boolean getBoolean (JSONObject json, String key, boolean defValue)
	{
		try {
			return json.getBoolean(key);
		}catch(Exception e)
		{
			return defValue;
		}
	}
}

师傅:邵发老师

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值