Jackson处理json使用记录

网上找半天找不到在原来的json后追加(append)json的写法,追加想了个。

 

package com.7mdm.json;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
import org.codehaus.jackson.annotate.JsonMethod;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig.Feature;
import org.codehaus.jackson.node.ObjectNode;

import cn.edu.hdu.computer.infoIntegrate.daoentity.UserResEntity;

/**
 * 
 * @author modm 
 * jackson demo
 * api文档   http://jackson.codehaus.org/1.9.0/javadoc/index.html
 */
public class JacksonDemo {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
		try {
			/**
			 * 通过类的数据结构来读取json数据
			 */
			// UrlDAOEntity url = mapper.readValue(new File("d:\\user.json"),
			// UrlDAOEntity.class);
			// System.out.println(url.getUserHash());
			/**
			 * 通过map写入json1,会覆盖旧数据
			 */
//			Map userData = new HashMap();
//			Map nameStruct = new HashMap();
//			nameStruct.put("first", "Joe");
//			nameStruct.put("last", "Sixpack");
//			userData.put("name", nameStruct);
//			userData.put("gender", "MALE");
//			userData.put("verified", Boolean.FALSE);
//			userData.put("userImage", "Rm9vYmFyIQ==");
//			mapper.writeValue(new File("d:\\user-modified.json"), userData);

			/**
			 * 通过map来写入json2,
			 */
//			mapper.setVisibility(JsonMethod.FIELD, Visibility.ANY);
//			mapper.configure(Feature.INDENT_OUTPUT, true);// 序列化输出
//			Map userResMap = new HashMap();
//			UserResEntity ure = new UserResEntity();
//			ure.setUserId(11);
//			ure.setUrl("www.baidu.com/s?wd=齐码代码");
//			ure.setUserHash("dsfdssgfdgfsd");
//			ure.setFileAttr("txt");
//			ure.setResState("N");
//			userResMap.put(ure.getUserId(), ure);
//			OutputStream os = new FileOutputStream(new File("d:\\UserURlRes.json"),true);//append
//			BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
//			mapper.writeValue(bw, userResMap);
			//String json = mapper.writeValueAsString(userResMap);
			//bw.write(json.replaceFirst("{", ","));

			/**
			 * 通过对象来写入json
			 */
//			mapper.setVisibility(JsonMethod.FIELD, Visibility.ANY);
//			mapper.configure(Feature.INDENT_OUTPUT, true);// 序列化输出
//			UserResEntity ure = new UserResEntity();
//			ure.setUserId(11);
//			ure.setUrl("www.baidu.com/s?wd=齐码代码");
//			ure.setUserHash("dsfdssgfdgfsd");
//			ure.setFileAttr("txt");
//			ure.setResState("N");
//			// System.out.println(mapper.writeValueAsString(userResMap));//return
//			// string
//			//FileWriter fw = new FileWriter(new File("d:\\UserURlRes.json"),true); // 用writer对象来写,可以append
//			OutputStream os = new FileOutputStream(new File("d:\\UserURlRes.json"),true);//append
//			BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
//			mapper.writeValue(bw, ure);

/**
 * 用map方式读取json
 */
//			InputStream is=new FileInputStream(new File("d:\\UserURlRes.json"));
//			BufferedReader br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
//			UserResEntity userResEntity=mapper.readValue(br, UserResEntity.class);
//			Map> map = mapper.readValue(br,new TypeReference>>() { });
//			System.out.println(map.get("33").get("url")); //用map的方式得到值

/**
* 通过objectNode方式读取json,可增加键值对
 */
//			InputStream is=new FileInputStream(new File("d:\\UserURlRes.json"));
//			BufferedReader br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
//			ObjectNode jNode = mapper.readValue(br,ObjectNode.class);
//			jNode.with("11").put("key1","value1"); //添加键值对
//			System.out.println(jNode);
/**
 * 用factory方式读,	有点像指针	
 */

//			JsonFactory f = new JsonFactory();
//			JsonParser jp = f.createJsonParser(new File("d:\\UserURlRes.json"));
//			//
//			//
//			while (jp.nextToken() !=null) {
//				String hashField =jp.getCurrentName();
//				jp.nextToken();// move to value
//				if ("22".equals(hashField)) {
//					while (jp.nextToken() != JsonToken.END_OBJECT) {
//						String userField =jp.getCurrentName();
//						jp.nextToken();// move to value
//						if ("url".equals(userField)) {
//
//							System.out.println(jp.getText());
//						}
//					}
//				}
//				//
//			}

/**
 * 在已有json数据之后,增加键值对demo
 * 
 */
			InputStream is=new FileInputStream(new File("d:\\UserURlRes.json"));
			BufferedReader br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
			ObjectNode jNode = mapper.readValue(br,ObjectNode.class);
			UserResEntity ure2 = new UserResEntity();
			ure2.setUserId(44);
			ure2.setUrl("www.baidu.com/s?wd=齐码代码44");
			ure2.setUserHash("dsfdssgfdgfsd");
			ure2.setFileAttr("txt");
			ure2.setResState("N");
			jNode.putPOJO(String.valueOf(ure2.getUserId()), ure2);
			OutputStream os = new FileOutputStream(new File("d:\\UserURlRes.json"),false);//append
			BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
			mapper.setVisibility(JsonMethod.FIELD, Visibility.ANY);
			mapper.configure(Feature.INDENT_OUTPUT, true);// 序列化输出
			mapper.writeValue(bw, jNode);

		} catch (JsonParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}

发表评论

电子邮件地址不会被公开。 必填项已用*标注