2012-12-26 63 views
2

请帮助我如何得到如下JSON输出:如何格式化JSON输出

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

相反的:

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

可能重复:http://stackoverflow.com/questions/6417758/is-there-a-possibility -to-hide-the-type-when-marshalling-subclasses-to?rq = 1 – Blender

+0

你可以添加关于你的对象模型的细节吗?然后我可以帮你删除继承指标。 –

+0

@Blender我不确定这是一个纯副本。这个问题也想改变变量名称。 –

回答

0

基于从你的问题的输出,您目前没有使用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

要使用莫西为您的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 
} 

更多信息