ObjectMapper 抛出 NullPointerException
ObjectMapper throw NullPointerException
这是我的代码:
Prueba test = new Prueba();
test.setNombre("test");
test.setApellidos("test");
test.setEdad("test");
try {
String pruebaTest = mapper.writeValueAsString(test);
System.out.println(pruebaTest);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
但这会抛出 NullPointerException,我不知道原因。
您需要初始化映射器/编写器:
//json object to string
ObjectMapper objectMapper = new ObjectMapper();
ObjectWriter ow = objectMapper.writer();
String jsonAsString;
try {
jsonAsString = ow.writeValueAsString(object);
} catch (final JsonProcessingException e) {
throw new Exception("Couldn't process object.", e);
}
您的代码:
//json object to string
ObjectMapper objectMapper = new ObjectMapper();
ObjectWriter ow = objectMapper.writer();
Prueba test = new Prueba();
test.setNombre("test");
test.setApellidos("test");
test.setEdad("test");
String pruebaTest;
try {
pruebaTest = ow.writeValueAsString(test);
System.out.println(pruebaTest);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
这是我的代码:
Prueba test = new Prueba();
test.setNombre("test");
test.setApellidos("test");
test.setEdad("test");
try {
String pruebaTest = mapper.writeValueAsString(test);
System.out.println(pruebaTest);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
但这会抛出 NullPointerException,我不知道原因。
您需要初始化映射器/编写器:
//json object to string
ObjectMapper objectMapper = new ObjectMapper();
ObjectWriter ow = objectMapper.writer();
String jsonAsString;
try {
jsonAsString = ow.writeValueAsString(object);
} catch (final JsonProcessingException e) {
throw new Exception("Couldn't process object.", e);
}
您的代码:
//json object to string
ObjectMapper objectMapper = new ObjectMapper();
ObjectWriter ow = objectMapper.writer();
Prueba test = new Prueba();
test.setNombre("test");
test.setApellidos("test");
test.setEdad("test");
String pruebaTest;
try {
pruebaTest = ow.writeValueAsString(test);
System.out.println(pruebaTest);
} catch (JsonProcessingException e) {
e.printStackTrace();
}