【第14篇】通过GSON的JsonReader去读取数据处理json数据

package ivyy.taobao.com.domain.gson;

import ivyy.taobao.com.utils.IoUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;

/**
 *@DEMO:json
 *@Author:jilongliang
 *@Date:2013-7-20
 */
public class JsonRead {
	private static Gson gson=new Gson();
	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception{
		 getJsonData();//读取数据
         
        String pathname=JsonRead.class.getClassLoader().getResource("doc/json.json").getPath();;
 		
        InputStream input = new FileInputStream(new File(pathname));
 		//String flag="m";//方法一
        String flag="input";//方法二
 		String content=IoUtils.reader(pathname);
 		if(flag.equals("m")){
 			readJsonData(input,content);
 		}else if(flag.equals("input")){
 			readJsonData(input,flag);
 		}
 		
	}
	/**
	 * 组装Json数据
	 * @throws Exception
	 */
	private static void getJsonData() throws Exception {
		/**
		  * 组装address对象的数据
		  */
		 Map address = new HashMap (); 
		 address.put("province", "广东省");
		 address.put("city", "云浮市");
		 address.put("district", "云城区");
		 address.put("street", "云城区闻莺路东升布艺"); 
		 /**
		  * 组装users对象的数据
		  */
		 Map users = new HashMap (); 
		 users.put("username", "liangjilong");
		 users.put("age", "25");
		 users.put("tel", "1361111111");
		 users.put("email", "[email protected]"); 
		 
		 Map listsObj = new HashMap (); 
		 listsObj.put("address",address);//address节点
		 listsObj.put("users",users);//users节点
		 
		 Object obj=listsObj;//转换成对象
		 
		 Map info = new HashMap (); 
		 info.put("info", obj);//json的根节点
		 
		 
         String json=gson.toJson(info);//转换成json数据
         System.out.println(json);//打印json数据
         readJsonData(null,json);
	}
	/**
	 * 从文件读取json数据
	 * @param in 输入流
	 * @throws Exception
	 */
	public static void readJsonData(InputStream in,String jsonFrom) throws Exception {
		JsonReader reader=null;
		if(jsonFrom.equals("input")){
			 reader = new JsonReader(new InputStreamReader(in, "gbk"));
		}else{
			reader = new JsonReader(new StringReader(jsonFrom));
		}
		try {
			reader.beginObject();
			String tagName = reader.nextName();
			if (tagName.equals("info")) {
				readInfo(reader);
			}
			reader.endObject();
		} finally {
			reader.close();
		}
	}
	/**
	 * 读取json的父(根,第一个)节点
	 * @param reader
	 * @throws Exception
	 */
	public static void readInfo(JsonReader reader) throws Exception {
		reader.beginObject();
		while (reader.hasNext()) {
			String tagName = reader.nextName();
			if (tagName.equals("address")) {
				readAddress(reader);
			} else if (tagName.equals("users")) {
				readUsers(reader);
			} 
		}
		reader.endObject();
	}
	/**
	 * 读取用户信息值
	 * @param reader
	 * @throws IOException
	 */
	public static void readUsers(JsonReader reader) throws IOException {
		reader.beginObject();
		while (reader.hasNext()) {
			String tag = reader.nextName();
			if (tag.equals("username")) {
				String username = reader.nextString();
				System.out.println("用户名:" + username);
			} else if (tag.equals("email")) {
				String email = reader.nextString();
				System.out.println("Email:" + email);
			} else if (tag.equals("tel")) {
				String tel = reader.nextString();
				System.out.println("电话:" + tel);
			}else if (tag.equals("age")) {
				String age = reader.nextString();
				System.out.println("年龄:" + age);
			} else {
				reader.skipValue();//忽略值/跳过break
			}
		}
		reader.endObject();
	}
	/**
	 * 读取地区值
	 * @param reader
	 * @throws IOException
	 */
	public static void readAddress(JsonReader reader) throws IOException {
		reader.beginObject();
		while (reader.hasNext()) {
			String tag = reader.nextName();
			if (tag.equals("province")) {
				String province = reader.nextString();
				System.out.println("省份:" + province);
			} else if (tag.equals("city")) {
				String city = reader.nextString();
				System.out.println("街道:" + city);
			} else if (tag.equals("street")) {
				String street = reader.nextString();
				System.out.println("街道:" + street);
			}else if (tag.equals("district")) {
				String district = reader.nextString();
				System.out.println("区:" + district);
			} else {
				reader.skipValue();//忽略值/跳过break
			}
		}
		reader.endObject();
	}
}
package ivyy.taobao.com.utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.OutputStreamWriter;
import java.io.Writer;

/**
 *@Author:liangjilong
 *@Date:2015-1-5
 *@Version:1.0
 *@Description:
 */
public class IoUtils {

	/**
	 * 读文件流
	 * 
	 * @param formPath从哪里读取的文件路径
	 * @return
	 */
	public static String reader(String formPath) {
		String content="";
		FileReader read = null;
		BufferedReader reader = null;
		try {
			read = new FileReader(new File(formPath));
			reader = new BufferedReader(read);
			StringBuffer buffer = new StringBuffer("");
			content = reader.readLine();
			while (content != null) {
				buffer.append(content).append("\n");
				content = reader.readLine();
			}
			return content = buffer.toString();// 返回
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (reader != null)
					reader.close();
				if (read != null)
					read.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return "";// 没值就返回空
	}
	
	/**
	 * 处理文件写
	 * @param content
	 * @param htmlPath
	 * @return
	 */
	public static boolean write(String content, String htmlPath) {  
        boolean flag = true;  
        try {  
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(htmlPath), "utf-8"));  
            out.write("\n" + content);  
            out.close();  
        } catch (Exception ex) {  
            ex.printStackTrace();  
            return false;  
        }  
        return flag;  
    } 
}

{
    "info": {
        "users": {
            "username": "东升布艺",
            "email": "[email protected]",
            "tel": "111111111",
            "age": "25"
        },
        "address": {
            "street": "云城区闻莺路东升布艺",
            "province": "广东省",
            "district": "云城区",
            "city": "云浮市"
        }
    }
}


你可能感兴趣的:(Json)