package com.javaniu.json;

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

import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonToken;
import org.codehaus.jackson.map.JsonMappingException;

public class JsonGeneratorAndParser {

    /**
     * @param args
     */
    public static void main(String[] args) {
	try {

	    JsonFactory jfactory = new JsonFactory();

	    /*** write to file ***/
	    JsonGenerator jGenerator = jfactory.createJsonGenerator(new File(
		    "c:/user.json"), JsonEncoding.UTF8);
	    jGenerator.writeStartObject(); // {

	    jGenerator.writeStringField("name", "java牛"); // "name" : "java牛"
	    jGenerator.writeNumberField("age", 29); // "age" : 29

	    jGenerator.writeFieldName("messages"); // "messages" :
	    jGenerator.writeStartArray(); // [

	    jGenerator.writeString("msg 1"); // "msg 1"
	    jGenerator.writeString("msg 2"); // "msg 2"
	    jGenerator.writeString("msg 3"); // "msg 3"

	    jGenerator.writeEndArray(); // ]

	    jGenerator.writeEndObject(); // }

	    jGenerator.close();

	    JsonParser jParser = jfactory.createJsonParser(new File(
		    "c:/user.json"));

	    // loop until token equal to "}"
	    while (jParser.nextToken() != JsonToken.END_OBJECT) {

		String fieldname = jParser.getCurrentName();
		if ("name".equals(fieldname)) {

		    // current token is "name",
		    // move to next, which is "name"'s value
		    jParser.nextToken();
		    System.out.println(jParser.getText());

		}

		if ("age".equals(fieldname)) {

		    // current token is "age",
		    // move to next, which is "name"'s value
		    jParser.nextToken();
		    System.out.println(jParser.getIntValue()); // display 29

		}

		if ("messages".equals(fieldname)) {

		    jParser.nextToken(); // current token is "[", move next

		    // messages is array, loop until token equal to "]"
		    while (jParser.nextToken() != JsonToken.END_ARRAY) {

			// display msg1, msg2, msg3
			System.out.println(jParser.getText());

		    }

		}

	    }
	    jParser.close();

	} catch (JsonGenerationException e) {

	    e.printStackTrace();

	} catch (JsonMappingException e) {

	    e.printStackTrace();

	} catch (IOException e) {

	    e.printStackTrace();

	}

    }
}
最近下载更多
wyx065747  LV67 2017年11月18日
mzoai  LV19 2017年7月31日
peyrong  LV1 2014年9月7日
chengcheng  LV2 2014年4月18日
lingling1420q  LV17 2014年4月5日
jiajian_22  LV19 2014年2月19日
菜鸟战斗  LV23 2013年8月22日
blackworm  LV3 2013年5月18日
ahtl  LV2 2013年4月27日
最近浏览更多
xluser  LV2 2020年10月15日
wangyangNN  LV2 2020年8月3日
丶小帅丶 2020年5月11日
暂无贡献等级
做自己的太阳  LV11 2020年3月29日
jaflkjlkfdjl  LV6 2019年11月12日
爷爷在此  LV16 2019年11月5日
王明科  LV4 2019年11月4日
allcom  LV1 2019年10月17日
孤寒双月泪  LV14 2018年6月7日
cjiankai  LV6 2018年6月5日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友