如何格式化Json输出

时间:2012-12-26 22:30:40

标签: json eclipselink moxy

请帮助我如何获得JSON输出如下:

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

而不是:

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

1 个答案:

答案 0 :(得分: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
}

了解更多信息