2013-03-14 132 views
2

我生成的JSON列表中有一個名爲<>的成員。這是編組確定。包含一個元素的jaxb列表

但是,我的消費(第三方)抱怨缺少[]對,當列表只有一個元素。我產生像:

"mylist":{"id":104,"name":"Only one found"} // produced 

,而我的消費者期望:

"mylist":[{"id":104,"name":"Only one found"}] // expected by third party 

是我的執行產生不正確的JSON?

回答

3

備註:我是EclipseLink JAXB (MOXy)的領導者,也是JAXB (JSR-222)專家組的成員。 JAXB(JSR-222)規範不包括JSON綁定。您看到的行爲很可能是由於JAXB實現與Jettison之類的庫一起使用。 Jettison將StAX事件轉換爲JSON或從JSON轉換StAX事件,並且只能在元素出現多次時才能檢測列表(請參閱:http://blog.bdoughan.com/2011/04/jaxb-and-json-via-jettison.html)。的EclipseLink JAXB提供原生JSON約束力,能正確表示大小的數組1.

Java模型

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

@XmlAccessorType(XmlAccessType.FIELD) 
public class Foo { 

    private List<Bar> mylist; 

} 

酒吧

import javax.xml.bind.annotation.*; 

@XmlAccessorType(XmlAccessType.FIELD) 
public class Bar { 

    private int id; 
    private String name; 

} 

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 

DEMO CODE

演示

import java.util.*; 
import javax.xml.bind.*; 
import javax.xml.transform.stream.StreamSource; 
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[] {Foo.class}, properties); 

     Unmarshaller unmarshaller = jc.createUnmarshaller(); 
     StreamSource json = new StreamSource("src/forum15404528/input.json"); 
     Foo foo = unmarshaller.unmarshal(json, Foo.class).getValue(); 

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

} 

input.json /輸出

我們看到,mylist被正確地表示爲JSON陣列。

{ 
    "mylist" : [ { 
     "id" : 104, 
     "name" : "Only one found" 
    } ] 
} 

附加信息

+1

感謝您詳盡的回答。讚賞。 – 2013-03-14 11:01:08

+0

由於Blaise暗示了具體的實現,我在TomEE論壇上提問。似乎在我現在使用的TomEE + 1.5.1之前有一個問題:http://openejb.979440.n4.nabble.com/json-list-returning-one-element-lacks-square-bracket-pair-tc4661524 html的。我的問題沒有解決(但),但現在我知道如何解決它。 – 2013-03-15 07:00:49

相關問題