2011-10-18 35 views
2

我對RestEasy和JAXB都是新手。我認爲,只要您控制要通過Web服務公開的所有來源,它們都非常易於使用。RestEasy JAXB - 使用XML公開第三方類

但現在我有一個問題。我有數據傳輸對象,我不能(不應該)用JAXB註釋進行註釋,但我仍然希望他們編組爲XML。

最簡單的方法或最佳做法是什麼?

任何幫助或評論表示讚賞。

巴拉茲

回答

0

注:我是EclipseLink JAXB (MOXy)鉛和JAXB 2 (JSR-222)專家小組的成員。

您可以使用MOXy的映射文檔JAXB擴展來提供元數據。然後,您可以在JAX-RS中使用ContextResolver來引導JAXBContext

package blog.bindingfile.jaxrs; 

import java.io.*; 
import java.util.*; 

import javax.ws.rs.Produces; 
import javax.ws.rs.ext.ContextResolver; 
import javax.ws.rs.ext.Provider; 
import javax.xml.bind.JAXBContext; 
import javax.xml.bind.JAXBException; 

import org.eclipse.persistence.jaxb.JAXBContextFactory; 

import blog.bindingfile.Customer; 

@Provider 
@Produces({"application/xml", "application/json"}) 
public class CustomerContextResolver implements ContextResolver<JAXBContext> { 

    private JAXBContext jc; 

    public CustomerContextResolver() { 
     ClassLoader cl = Customer.class.getClassLoader(); 
     Map<String, Object> props = new HashMap<String, Object>(1); 
     props.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, "blog/bindingfile/binding.xml"); 
     jc = JAXBContext.newInstance(new Class[] {Customer.class} , props); 
    } 

    public JAXBContext getContext(Class<?> clazz) { 
     if(Customer.class == clazz) { 
      return jc; 
     } 
     return null; 
    } 

} 

進行了詳細的實施例

+0

謝謝,我會盡快嘗試一下。這看起來像我正在尋找的。 –

1

我有同樣的問題:我從持久層得到了取出實體對象(已經用實際數據),但是它們來自第三方類,我不能用@XmlRootElement註釋,也不能更改獲取代碼。

對我來說,簡單地把它們包裝在JAXBElement這個伎倆。所以,RESTful方法:

@GET 
@Path("/listAll") 
@Produces(MediaType.APPLICATION_XML); // "application/xml" 
public List<Person> getPersonList() { 
    return persistenceLayer.fetchAllPerson(); 
} 

時改爲任職:

@GET 
@Path("/listAll") 
@Produces(MediaType.APPLICATION_XML); // "application/xml" 
public List<JAXBElement<Person>> getPersonList() { 
    List<Person> ps = persistenceLayer.fetchAllPerson(); 
    List<JAXBElement<Person>> jaxbeps = new ArrayList<JAXBElement<Person>>(ps.size()); 
    for (Person p : ps) { 
     jaxbeps.add(jaxbeWrapp(p)); 
    } 
    return jaxbeps; 
} 

和使用的通用方法(你可以內嵌它,當然):

public static <T> JAXBElement<T> jaxbeWrapp(T obj) { 
    Class<T> clazz = (Class<T>) obj.getClass(); 
    return new JAXBElement<T>(new QName(obj.getClass().getName().toLowerCase()), clazz, obj); 
} 

這就是它!希望能幫助到你!