日期:2014-05-16  浏览次数:20425 次

通过codehaus来实现json写入文件和读取文件成json对象

pom.xml需要增加如下依赖:

<dependency> 
<groupId>org.codehaus.jackson</groupId> 
<artifactId>jackson-core-lgpl</artifactId> 
<version>1.9.1</version> 
</dependency> 
<dependency> 
<groupId>org.codehaus.jackson</groupId> 
<artifactId>jackson-mapper-lgpl</artifactId> 
<version>1.9.1</version> 
</dependency>

?

package com.zuidaima.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();

	}

    }
}

	    			

?
转载请标明出处:通过codehaus来实现json写入文件和读取文件成json对象