문자열을 마샬링 할 때 필드 값으로 'null'을 인쇄 할 수 있습니까?마샬링하는 동안 JAXB null 빈 문자열 대신
예 : 오류 및 error_code는 문자열이며, 값/오류가 서버 측에서 발생했음을 나타내는 값으로 'null'을 사용하고 싶습니다.
{
"error_code": null,
"error": null
}
오늘은 "ERROR_CODE"또는 "오류"그래서이 필드는 일반적으로 JSON에 해당, 그들은 명시 적으로 this.errorCode = StringUtils.EMPTY로 초기화되지 않은 경우, 빈 값을 사용해야합니다;
{
"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, 내가 생각 그래서 오늘, 나는 다음 JSON을 이것은 잠재적으로 나를 도울 수있다. 그러나 아무 것도 :
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;
}
}
도움말해야 다음 http://blog.bdoughan.com/2012/04/binding-to-json-xml -handling-null.html –
@BlaiseDoughan 기본적으로 다음과 같이 @XmlElement 요소로 정의 된 POJO 필드가 있습니다. @XmlElement (nillable = true) private String error_code; 출력을 application/xml로 표시하면 올바른 값을 얻습니다. 그러나 나는 얻을 출력으로 응용 프로그램/JSON을 사용하는 경우 : ' "상태 ": { "@nil ":"true "로 } ' 잘못된 것 같다. JSON 사양에 따르면 더 비슷합니다 : "error_code": null 어떻게 해결할 수 있습니까? –
IgorA
MOXy를 JSON 공급자로 사용하여 유스 케이스를 구현할 수있는 방법을 보여주는 답변을 추가했습니다. –