2

请帮助我如何获取 JSON 输出,如下所示:

{
   "_costMethod": "Average",
   "fundingDate": 2008-10-02,
   "fundingAmount": 2510959.95
}

代替:

{
   "@type": "sma",
   "costMethod": "Average",
   "fundingDate": "2008-10-02",
   "fundingAmount": "2510959.95"
}
4

1 回答 1

1

根据您的问题的输出,您当前没有使用EclipseLink JAXB (MOXy)的本机 JSON 绑定。以下应该会有所帮助。

Java 模型

以下是我根据您的帖子对您​​的对象模型的最佳猜测。我添加了获取您正在寻找的输出所需的元数据。

  • @XmlElement注释可用于更改键的名称。
  • 我使用@XmlSchemaType注解来控制Date属性的格式。

package forum14047050;

import java.util.Date;
import javax.xml.bind.annotation.*;

@XmlType(propOrder={"costMethod", "fundingDate", "fundingAmount"})
public class Sma {

    private String costMethod;
    private Date fundingDate;
    private double fundingAmount;

    @XmlElement(name="_costMethod")
    public String getCostMethod() {
        return costMethod;
    }

    public void setCostMethod(String costMethod) {
        this.costMethod = costMethod;
    }

    @XmlSchemaType(name="date")
    public Date getFundingDate() {
        return fundingDate;
    }

    public void setFundingDate(Date fundingDate) {
        this.fundingDate = fundingDate;
    }

    public double getFundingAmount() {
        return fundingAmount;
    }

    public void setFundingAmount(double fundingAmount) {
        this.fundingAmount = fundingAmount;
    }

}

jaxb.properties

要将 MOXy 用作您的 JAXB (JSR-222) 提供程序,您需要包含一个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 forum14047050;

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

public class Demo {

    public static void main(String[] args) throws Exception {
        Map<String, Object> properties = new HashMap<String, Object>(2);
        properties.put(JAXBContextProperties.MEDIA_TYPE, "application/json");
        properties.put(JAXBContextProperties.JSON_INCLUDE_ROOT, false);
        JAXBContext jc = JAXBContext.newInstance(new Class[] {Sma.class}, properties);

        Sma sma = new Sma();
        sma.setCostMethod("Average");
        sma.setFundingDate(new Date(108, 9, 2));
        sma.setFundingAmount(2510959.95);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(sma, System.out);
    }

}

输出

下面是运行演示代码的输出。与您的问题不同,我在日期值周围有引号。这是使其成为有效 JSON 所必需的。

{
   "_costMethod" : "Average",
   "fundingDate" : "2008-10-02",
   "fundingAmount" : 2510959.95
}

了解更多信息

于 2012-12-31T11:44:38.473 回答