标签归档:json

JSONPath对JSON的解析,与之XPath

JSONPath: https://github.com/jayway/JsonPath

Java DSL for reading and testing JSON documents

下面是一个json数据,而下面表格中是对应的插件的识别字符串,想必就会明白用JSONPath来解析json的路径问题了吧。不会的联系我。

{
    "store": {
        "book": [
            {
                "category": "reference",
                "author": "Nigel Rees",
                "title": "Sayings of the Century",
                "price": 8.95
            },
            {
                "category": "fiction",
                "author": "Evelyn Waugh",
                "title": "Sword of Honour",
                "price": 12.99
            },
            {
                "category": "fiction",
                "author": "Herman Melville",
                "title": "Moby Dick",
                "isbn": "0-553-21311-3",
                "price": 8.99
            },
            {
                "category": "fiction",
                "author": "J. R. R. Tolkien",
                "title": "The Lord of the Rings",
                "isbn": "0-395-19395-8",
                "price": 22.99
            }
        ],
        "bicycle": {
            "color": "red",
            "price": 19.95
        }
    }
}

 

XPath JSONPath Result
/store/book/author $.store.book[*].author the authors of all books in the store
//author $..author all authors
/store/* $.store.* all things in store, which are some books and a red bicycle.
/store//price $.store..price the price of everything in the store.
//book[3] $..book[2] the third book
//book[last()] $..book[(@.length-1)]
$..book[-1:]
the last book in order.
//book[position()<3] $..book[0,1]
$..book[:2]
the first two books
//book[isbn] $..book[?(@.isbn)] filter all books with isbn number
//book[price<10] $..book[?(@.price<10)] filter all books cheapier than 10
//* $..* all Elements in XML document. All members of JSON structure.

 

 

解决ie6浏览器,JSON未定义错误

ie6 這個微軟一直遲遲不更新的瀏覽器, 已經需要被淘汰的版本, 卻因為微軟壟斷市場不求進步而沿用至今!
造成目前google, safari, 與firefox..等瀏覽器都慢慢吃掉IE市佔! 微軟才拼命推出更新, 真的是要壓力才會進步…
win7已經搭配最新IE8, 這是好事! 各家公司推出自己最棒的產品互相競爭

 

IE6 我遇到了 json 未定義的問題! 其實是因為我有使用jquery當中有包含json的內容
google了一下發現不難解決, 紀錄一下:

去下载一个json2.js这个文件加到所在页面就可以了
官網
http://www.json.org/

裡面有json2下載點
https://github.com/douglascrockford/JSON-js


使用方式:
< script type="text/javascript" src="json2.js">< /script>

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();
		}

	}

}