如何在編組字符串時將'null'打印爲字段值?JAXB null在封送處理過程中改爲空字符串
示例:error和error_code是字符串,我想使用'null'作爲值,表示服務器端沒有值/錯誤發生。
{
"error_code": null,
"error": null
}
今天,我必須使用空值,從而使「ERROR_CODE」或「錯誤」,這些領域一般分爲JSON,如果他們沒有明確初始化爲this.errorCode = StringUtils.EMPTY; 所以今天,我有下一個JSON:
{
"error_code": "",
"error": ""
}
這是怎麼看起來在代碼:
@XmlRootElement()
@XmlAccessorType(XmlAccessType.FIELD)
public class Response
{
@SuppressWarnings("unused")
private static final Logger log = LoggerFactory.getLogger(Response.class);
public static final String ERROR_FIELD_NAME = "error";
public static final String ERROR_CODE_FIELD_NAME = "error_code";
// @XmlJavaTypeAdapter(CafsResponse.EmptyStringAdapter.class)
@XmlElement(name = Response.ERROR_CODE_FIELD_NAME)
private String errorCode;
// @XmlJavaTypeAdapter(CafsResponse.EmptyStringAdapter.class)
@XmlElement(name = Response.ERROR_FIELD_NAME)
private String errorMessage;
// Empty Constructor
public Response()
{
this.errorCode = StringUtils.EMPTY; // explicit initialization, otherwise error_code will not appear as part of json, how to fix this this ?
this.errorMessage = StringUtils.EMPTY;
}
等等
// Empty Constructor
public Response()
{
this.errorCode = null; // this variant dosn't work either, and error_code again didn't get to json
this.errorMessage = null;
}
見,@XmlJavaTypeAdapter,我想這可能會幫助我 - 但沒有:)
而不是空值,我得到「空」作爲字符串。
if (StringUtils.isEmpty(str))
{
return null;
}
return str;
{
"error_code": "null", // this is not whta i wanted to get.
"error": "null"
}
對此有何幫助? - 問我有沒有不清楚的地方。
名單:
/**
* Empty string Adapter specifying how we want to represent empty strings
* (if string is empty - treat it as null during marhsaling)
*
*/
@SuppressWarnings("unused")
private static class EmptyStringAdapter extends XmlAdapter<String, String>
{
@Override
public String unmarshal(String str) throws Exception
{
return str;
}
@Override
public String marshal(String str) throws Exception
{
if (StringUtils.isEmpty(str))
{
return null;
}
return str;
}
}
以下應該有所幫助:http://blog.bdoughan.com/2012/04/binding-to-json-xml -handling-null.html –
@BlaiseDoughan 基本上我有一些POJO字段,用@XmlElement元素定義如下: @XmlElement(nillable = true)private String error_code;我得到正確的值: 然而,當我使用的應用程序/ JSON作爲輸出我得到: ' 」狀態「:{ 」@nil「: 」真正的「 } ' 這似乎不正確。根據JSON規範,它更像: 「error_code」:null 如何解決此問題? –
IgorA
我已經添加了一個答案,演示如何使用MOXY作爲您的JSON提供程序來實現您的用例。 –