Jackson流式API
作者:互联网
public
class
JacksonTester {
public
static
void
main(String args[]){
JacksonTester tester =
new
JacksonTester();
try
{
JsonFactory jasonFactory =
new
JsonFactory();
JsonGenerator jsonGenerator = jasonFactory.createJsonGenerator(
new
File(
"student.json"
), JsonEncoding.UTF8);
// {
jsonGenerator.writeStartObject();
// "name" : "Mahesh Kumar"
jsonGenerator.writeStringField(
"name"
,
"Mahesh Kumar"
);
// "age" : 21
jsonGenerator.writeNumberField(
"age"
,
21
);
// "verified" : false
jsonGenerator.writeBooleanField(
"verified"
,
false
);
// "marks" : [100, 90, 85]
jsonGenerator.writeFieldName(
"marks"
);
// [
jsonGenerator.writeStartArray();
// 100, 90, 85
jsonGenerator.writeNumber(
100
);
jsonGenerator.writeNumber(
90
);
jsonGenerator.writeNumber(
85
);
// ]
jsonGenerator.writeEndArray();
// }
jsonGenerator.writeEndObject();
jsonGenerator.close();
//result student.json
//{
// "name":"Mahesh Kumar",
// "age":21,
// "verified":false,
// "marks":[100,90,85]
//}
ObjectMapper mapper =
new
ObjectMapper();
Map<String,Object> dataMap = mapper.readValue(
new
File(
"student.json"
), Map.
class
);
System.out.println(dataMap.get(
"name"
));
System.out.println(dataMap.get(
"age"
));
System.out.println(dataMap.get(
"verified"
));
System.out.println(dataMap.get(
"marks"
));
}
catch
(JsonParseException e) {
e.printStackTrace();
}
catch
(JsonMappingException e) {
e.printStackTrace();
}
catch
(IOException e) {
e.printStackTrace();
}
}
}
junit testpublic class JsonStreamTest {
@Test
public void read() throws JsonParseException, IOException{
JsonFactory factory = new JsonFactory();
InputStream is = this.getClass().getClassLoader().getResourceAsStream("user.json");
JsonParser jsonParse = factory.createJsonParser(is);
User user = new User();
JsonToken token = jsonParse.nextToken();
if(token==JsonToken.START_OBJECT){
while((jsonParse.nextToken())!=JsonToken.END_OBJECT){
String fieldName = jsonParse.getCurrentName();
jsonParse.nextToken();
if("name".equalsIgnoreCase(fieldName)){
Name name = new Name();
while(jsonParse.nextToken()!=JsonToken.END_OBJECT){
if(jsonParse.getCurrentName().equals("first")){
name.setFirst(jsonParse.getText());
}
if(jsonParse.getCurrentName().equals("last")){
name.setLast(jsonParse.getText());
}
}
user.setName(name);
}else if("gender".equals(fieldName)){
String text = jsonParse.getText();
user.setGender(Gender.valueOf(text));
}else if("verified".equals(fieldName)){
user.setVerified(jsonParse.getBooleanValue());
}else if("userImage".equals(fieldName)){
user.setUserImage(jsonParse.getBinaryValue());
}
}
}
jsonParse.close();
}
标签:Jackson,name,jsonGenerator,jsonParse,API,流式,new,dataMap,user 来源: https://www.cnblogs.com/dogdogwang/p/10792204.html