2012-07-03 2 views
1

문자열을 마샬링 할 때 필드 값으로 '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; 
     } 

} 
+1

도움말해야 다음 http://blog.bdoughan.com/2012/04/binding-to-json-xml -handling-null.html –

+0

@BlaiseDoughan 기본적으로 다음과 같이 @XmlElement 요소로 정의 된 POJO 필드가 있습니다. @XmlElement (nillable = true) private String error_code; 출력을 application/xml로 표시하면 올바른 값을 얻습니다. 그러나 나는 얻을 출력으로 응용 프로그램/JSON을 사용하는 경우 : ' "상태 ": { "@nil ":"true "로 } ' 잘못된 것 같다. JSON 사양에 따르면 더 비슷합니다 : "error_code": null 어떻게 해결할 수 있습니까? – IgorA

+0

MOXy를 JSON 공급자로 사용하여 유스 케이스를 구현할 수있는 방법을 보여주는 답변을 추가했습니다. –

답변

0

참고 : 나는 EclipseLink JAXB (MOXy) 리드와 JAXB (JSR-222) 전문가 그룹의 구성원입니다.

JSON 공급자로 MOXy를 사용하여이 사용 사례를 지원할 수 있습니다. 속성을 마샬링합니다

목시는 (: http://blog.bdoughan.com/2012/04/binding-to-json-xml-handling-null.html 참조) 찾고있는 표현으로 @XmlElement(nillable=true) 표시

응답 : 다음은 예입니다.

package forum11319741; 

import javax.xml.bind.annotation.*; 

@XmlRootElement 
@XmlAccessorType(XmlAccessType.FIELD) 
public class Response { 

     public static final String ERROR_FIELD_NAME = "error"; 
     public static final String ERROR_CODE_FIELD_NAME = "error_code"; 

     @XmlElement(name = Response.ERROR_CODE_FIELD_NAME, nillable = true) 
     private String errorCode; 

     @XmlElement(name = Response.ERROR_FIELD_NAME, nillable = true) 
     private String errorMessage; 

} 

jaxb.속성

는 (: http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html 참조) : 다음 항목으로 도메인 모델과 동일한 패키지에 jaxb.properties라는 파일을 포함 할 필요가 당신의 JAXB 공급자로 MOXY를 사용하려면

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory 

데모

package forum11319741; 

import javax.xml.bind.*; 

public class Demo { 

    public static void main(String[] args) throws Exception { 
     JAXBContext jc = JAXBContext.newInstance(Response.class); 

     Marshaller marshaller = jc.createMarshaller(); 
     marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); 
     marshaller.setProperty("eclipselink.media-type", "application/json"); 
     marshaller.setProperty("eclipselink.json.include-root", false); 

     Response response = new Response(); 
     marshaller.marshal(response, System.out); 
    } 

} 

출력

{ 
    "error_code" : null, 
    "error" : null 
} 

MOXY 및 JAX-RS

당신은 당신의 JAX-RS 응용 프로그램에서 JSON 공급자로 MOXY를 활성화 MOXyJsonProvider 클래스를 사용할 수 있습니다 (참조 : http://blog.bdoughan.com/2012/05/moxy-as-your-jax-rs-json-provider.html을). 추가 정보

package org.example; 

import java.util.*; 
import javax.ws.rs.core.Application; 
import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider; 

public class CustomerApplication extends Application { 

    @Override 
    public Set<Class<?>> getClasses() { 
     HashSet<Class<?>> set = new HashSet<Class<?>>(2); 
     set.add(MOXyJsonProvider.class); 
     set.add(CustomerService.class); 
     return set; 
    } 

} 

관련 문제