3

で注釈が付けられたJavaクラスがあります@XmlRootElement。このJavaクラスにはprivate long id、JavaScriptクライアントに返したいlongプロパティ()があります。

次のようにJSONを作成します。

MyEntity myInstance = new MyEntity("Benny Neugebauer", 2517564202727464120);
StringWriter writer = new StringWriter();
JSONConfiguration config = JSONConfiguration.natural().build();
Class[] types = {MyEntity.class};
JSONJAXBContext context = new JSONJAXBContext(config, types);
JSONMarshaller marshaller = context.createJSONMarshaller();
marshaller.marshallToJSON(myInstance, writer);
json = writer.toString();
System.out.println(writer.toString());

これが生成されます:

{"name":"Benny Neugebauer","id":2517564202727464120}

ただし、問題は、JavaScriptクライアントにはlong値が大きすぎることです。したがって、この値を文字列として返したいと思います(Javaで長い文字列を作成することはありません)。

以下を生成できるアノテーション(または同様のもの)はありますか?

{"name":"Benny Neugebauer","id":"2517564202727464120"}
4

1 に答える 1

2

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

以下は、JSONプロバイダーとしてMOXyを使用してこのユースケースを実現する方法です。

MyEntity

longプロパティに注釈を付けて、@XmlSchemaType(name="string")としてマーシャリングする必要があることを示しますString

package forum11737597;

import javax.xml.bind.annotation.*;

@XmlRootElement
public class MyEntity {

    private String name;
    private long id;

    public MyEntity() {
    }

    public MyEntity(String name, long id) {
        setName(name);
        setId(id);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @XmlSchemaType(name="string")
    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

}

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

デモ

サンプルコードを変更して、MOXyを使用した場合にどのように表示されるかを示します。

package forum11737597;

import java.io.StringWriter;
import java.util.*;
import javax.xml.bind.*;
import org.eclipse.persistence.jaxb.JAXBContextProperties;

public class Demo {

    public static void main(String[] args) throws Exception {
        MyEntity myInstance = new MyEntity("Benny Neugebauer", 2517564202727464120L);
        StringWriter writer = new StringWriter();
        Map<String, Object> config = new HashMap<String, Object>(2);
        config.put(JAXBContextProperties.MEDIA_TYPE, "application/json");
        config.put(JAXBContextProperties.JSON_INCLUDE_ROOT, false);
        Class[] types = {MyEntity.class};
        JAXBContext context = JAXBContext.newInstance(types, config);
        Marshaller marshaller = context.createMarshaller();
        marshaller.marshal(myInstance, writer);
        System.out.println(writer.toString());
    }

}

出力

以下は、デモコードの実行からの出力です。

{"id":"2517564202727464120","name":"Benny Neugebauer"}

詳細については

于 2012-07-31T11:00:28.643 に答える