1

文字列をマーシャリングするときに、フィールド値として「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;
        }

}
4

1 に答える 1

0

注: 私はEclipseLink JAXB (MOXy)のリーダーであり、JAXB (JSR-222)エキスパート グループのメンバーです。

MOXy を JSON プロバイダーとして使用して、このユース ケースをサポートできます。以下に例を示します。

応答

MOXy は、 でマークされ@XmlElement(nillable=true)たプロパティを探している表現にマーシャリングします (参照: http://blog.bdoughan.com/2012/04/binding-to-json-xml-handling-null.html )。

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.properties

MOXy を JAXB プロバイダーとして使用するにはjaxb.properties、次のエントリを使用して、ドメイン モデルと同じパッケージで呼び出されるファイルを含める必要があります ( http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-asを参照)。 -your.html ):

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

このクラスを使用してMOXyJsonProvider、JAX-RS アプリケーションで MOXy を JSON プロバイダーとして有効にすることができます ( 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;
    }

}

詳細については

于 2012-07-04T13:12:12.980 に答える