JSON之Jackson(二)

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


例子的源代码托管在:https://github.com/GatsbyNewton/jackson


你可能感兴趣的:(java,json,Jackson)