编组字符串时,如何将“null”打印为字段值?
示例:error 和 error_code 是字符串,我想使用“null”作为值,表示服务器端没有发生值/错误。
{
"error_code": null,
"error": null
}
今天不得不使用EMPTY值,这样“error_code”或者“error”这些字段一般都属于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;
}
ETC...
// 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,我认为这可能对我有帮助 - 但没有:)
我将“null”作为字符串而不是空值。
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;
}
}