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 に答える