import org.codehaus.jackson.*;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import java.io.File;
import java.io.IOException;
public class JacksonTest {
public static void main(String []args){
ObjectMapper objectMapper=new ObjectMapper();
String str="{\"id\":1,\"name\":\"张三\"}";
try {
People student=objectMapper.readValue(str,People.class);//将字符串转对象
System.out.println(student+"读取");
objectMapper.enable(SerializationConfig.Feature.INDENT_OUTPUT);
String jsonString = objectMapper.writeValueAsString(student); //将对象转为json字符串
System.out.println(jsonString);
//使用JsonGenerator来写json字符串 运行结果:{"name":"张三","id":10}
JsonFactory jsonFactory=new JsonFactory();
JsonGenerator jsonGenerator=jsonFactory.createJsonGenerator(new File("D:/people.json"), JsonEncoding.UTF8);
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField("name","张三");
jsonGenerator.writeNumberField("id",10);
jsonGenerator.writeEndObject();
jsonGenerator.close();
//使用JsonParser来读取json字符串
JsonParser jsonParser=jsonFactory.createJsonParser(new File("D:/people.json"));
while(jsonParser.nextToken()!= JsonToken.END_OBJECT){
String curname=jsonParser.getCurrentName();
if("name".equals(curname)){
jsonParser.nextToken();
System.out.println( jsonParser.getText());
}
if("id".equals(curname)){
jsonParser.nextToken();
System.out.println(jsonParser.getIntValue());
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}