1. 程式人生 > >JSON之Jackson(二)

JSON之Jackson(二)

1.Jackson JsonParser

Jackson JsonParser比Jackson ObjectMapper更底層,這就使得Jackson JsonParser比ObjectMapper更快,但是也更加笨重。Jackson JsonParser的工作方式是:將JSON分成一個記號序列,讓你迭代記號(Token)序列進行解析。Jackson Parser的Token有:

  1. START_OBJECT
  2. END_OBJECT
  3. START_ARRAY
  4. END_ARRAY
  5. FIELD_NAME
  6. VALUE_EMBEDDED_OBJECT
  7. VALUE_FALSE
  8. VALUE_TRUE
  9. VALUE_NULL
  10. VALUE_STRING
  11. VALUE_NUMBER_INT
  12. VALUE_NUMBER_FLOAT

這些Token在JsonToken類中,通過nextToken()獲取。

getCurrentName()獲取當前Field Name,而Value可以用getText()獲取,也可以用getValueAsString()、getValueAsInt()等類似的方法獲取。下面是一個簡單的例子:

user.json檔案:

{
  "name": {
    "first": "Joe",
    "last": "Sixpack"
  },
  "gender": "MALE",
  "verified": false,
  "userImage": "Rm9vYm"
}


示例程式碼:

public static void readFromFile(){
	String path = "F:\\Codes\\IDEA\\Tools\\data\\json\\user.json";
//        String carJson = "{ \"brand\" : \"Mercedes\", \"doors\" : 5 }";
	JsonFactory jsonFactory = new JsonFactory();
	User user = new User();

	try {
		JsonParser parser = jsonFactory.createParser(new File(path));
		parser.nextToken();    //進入JSON的“{”
		while (parser.nextToken() != JsonToken.END_OBJECT){
			String fieldName = parser.getCurrentName();
			parser.nextToken();
			if(fieldName.equals("name")) {
				System.out.println(fieldName + ":");
				while (parser.nextToken() != JsonToken.END_OBJECT) {
					parser.nextToken();
					String field = parser.getCurrentName();
					System.out.println("\t" + field + ": " + parser.getValueAsString());
				}
			}
			else {
				System.out.println(fieldName + ": " + parser.getText());
			}
		}
		parser.close();
	}
	catch (Exception e){
		e.printStackTrace();
	}
}


同Jackson ObjectMapper一樣,你也可以解析String、Reader、InputStream、URL、byte陣列、char陣列。

String carJson =
        "{ \"brand\" : \"Mercedes\", \"doors\" : 5 }";

JsonFactory factory = new JsonFactory();
JsonParser  parser  = factory.createParser(carJson);

2.Jackson Generator

Jackson Generator用於生成JSON。對於簡單的變數這種資料型別,Jackson Generator和Jackson JsonParser一樣從JsonFactory中建立。如:

// Write simple variables to file
public static void writeSimpleToFile(){

	JsonFactory jsonFactory = new JsonFactory();
	OutputStream outputStream = null;
//        Car car = new Car("BMW", 4, new Car.Owner("Gatsby", "Newton"), new String[]{"engine", "brake"});

	try {
		outputStream = new FileOutputStream("F:\\Codes\\IDEA\\Tools\\data\\json\\out\\generate_simple.json");
		JsonGenerator generator = jsonFactory.createGenerator(outputStream, JsonEncoding.UTF8);
		generator.writeStartObject();

		generator.writeStringField("brand", "Mercedes");
		generator.writeNumberField("doors", 5);
		generator.writeObjectFieldStart("owner");
		generator.writeStringField("first", "Gatsby");
		generator.writeStringField("last", "Newton");
		generator.writeEndObject();

		generator.writeArrayFieldStart("component");
		generator.writeString("engine");
		generator.writeString("brake");
		generator.writeEndArray();

		// Write a object.
//            generator.writeObjectField("owner", new Car.Owner("Gatsby", "Newton"));
//            generator.writeObjectField("component", new String[]{"engine", "brake"});

		generator.writeEndObject();

		generator.flush();
		generator.close();
	}
	catch (Exception e){
		e.printStackTrace();
	}
}


但是對於複雜的資料型別,Jackson Generator必須從ObjectMapper.getJsonFactory()的JsonFactory中建立,否則會報一下錯誤:

java.lang.IllegalStateException: No ObjectCodec defined for the generator,can only serialize simple wrapper types (type passed edu.wzm.jackson.Car$Owner)

其中,ObjectMapper.getJsonFactory()方法被標記為deprecated,不過這並沒有關係,這種情況在Java程式設計中經常遇到,這是可以用的。但是對於那種建議不要使用的方法,最好棄之不用。

// Write objects to file.
public static void writeComplexToFile(){

	// If you use JsonFactory jsonFactory = new JsonFactory(), it shows the error:
	// java.lang.IllegalStateException: No ObjectCodec defined for the generator,
	// can only serialize simple wrapper types (type passed edu.wzm.jackson.Car$Owner)
	JsonFactory jsonFactory = new ObjectMapper().getJsonFactory();

	OutputStream outputStream = null;
//        Car car = new Car("BMW", 4, new Car.Owner("Gatsby", "Newton"), new String[]{"engine", "brake"});

	try {
		outputStream = new FileOutputStream("F:\\Codes\\IDEA\\Tools\\data\\json\\out\\generate_complex.json");
		JsonGenerator generator = jsonFactory.createGenerator(outputStream, JsonEncoding.UTF8);
		generator.writeStartObject();

		generator.writeStringField("brand", "Mercedes");
		generator.writeNumberField("doors", 5);

		// Write a object.
		generator.writeObjectField("owner", new Car.Owner("Gatsby", "Newton"));
		generator.writeObjectField("component", new String[]{"engine", "brake"});

		generator.writeEndObject();

		generator.flush();
		generator.close();
	}
	catch (Exception e){
		e.printStackTrace();
	}
}