我在Jersey應用程序中使用Jackson進行JSON序列化/反序列化。我想在我的Java POJO屬性中將JSON中的空字符串讀取爲空值。我試圖在Object Mapper上設置DeserializationConfig.Feature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT,但它不起作用。這裏是低於Jackson對象映射器反序列化配置.Feature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT
import java.io.IOException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
public class TestMapper {
/**
* @param args
*/
public static void main(String[] args) {
TestMapper.testJson();
}
public static void testJson(){
String jsonString = "{\"name\":\"First Name\",\"phone\":\"\",\"unknown\":\"test\"}";
ObjectMapper result = new ObjectMapper();
//result.setDeserializationConfig(result.getDeserializationConfig().with(DeserializationConfig.Feature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT));
//result.enable(DeserializationConfig.Feature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
/*DeserializationConfig deserializeConfig = result.getDeserializationConfig();
deserializeConfig.with(DeserializationConfig.Feature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);*/
result.configure(DeserializationConfig.Feature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
result.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
try {
TestBean testBean = result.readValue(jsonString, TestBean.class);
if(testBean.getPhone()!=null&& testBean.getPhone().equals("")){
System.out.print("Phone Number is empty string");
}else{
System.out.print("Phone Number is null");
}
} catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
代碼的bean是如下
public class TestBean {
private String name;
private String phone;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public TestBean(String name, String phone) {
super();
this.name = name;
this.phone = phone;
}
public TestBean() {
super();
}
}
輸出始終
Phone Number is empty string
我不知道這是爲什麼不工作。我正在使用傑克遜1.9.2。
你有沒有調試過,看看手機有什麼價值? – Jay
是的值是「」 – user2957698
我有同樣的問題,任何解決方案?我正在使用傑克遜1.9 –