文字列をマーシャリングするときに、フィールド値として「null」を出力するにはどうすればよいですか?
例: error と error_code は文字列で、値がないことを示す値として「null」を使用したい/サーバー側でエラーが発生した。
{
"error_code": null,
"error": null
}
今日、「error_code」または「error」これらのフィールドが通常 json に分類されるように、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を参照してください、これは潜在的に私を助けることができると思いました-しかし、そうではありません:)
null 値の代わりに、文字列として「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;
}
}