如何返回长的特性与JAXB JSON字符串值(How to return a long proper

2019-09-20 12:50发布

我有注解的Java类@XmlRootElement 。 这个Java类有很长的特性( private long id ,我想回到一个JavaScript客户端)。

我创建了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客户端过大。 所以,我想这个值返回一个字符串(未做长在Java中的字符串)。

是否有一个注释(或类似的东西),可以产生以下?

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

Answer 1:

注:我是的EclipseLink JAXB(莫西)领导和成员JAXB(JSR-222)专家小组。

下面是你如何能做到与莫西这种使用情况下,您的JSON提供商。

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

要配置莫西为您的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 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"}

欲获得更多信息

  • http://blog.bdoughan.com/2011/08/json-binding-with-eclipselink-moxy.html


文章来源: How to return a long property as JSON string value with JAXB