2012-10-30 266 views
1

我有一個JSON響應,我需要的是將相應的JSON字符串映射到特定的Response類。是否有任何工具或框架可以做到這一點。JSON字符串到對象映射

Response類是:

import javax.xml.bind.annotation.XmlAccessType; 
import javax.xml.bind.annotation.XmlAccessorType; 
import javax.xml.bind.annotation.XmlElement; 
import javax.xml.bind.annotation.XmlRootElement; 

@XmlRootElement(name = "0") 
@XmlAccessorType(XmlAccessType.FIELD) 
public class Student { 

    @XmlElement(name="0") 
    private String firstName; 
    @XmlElement(name="1") 
    private String lastName; 

    public String getFirstName() { 
     return firstName; 
    } 
    public void setFirstName(String firstName) { 
     this.firstName = firstName; 
    } 
    public String getLastName() { 
     return lastName; 
    } 
    public void setLastName(String lastName) { 
     this.lastName = lastName; 
    } 
} 

JSON響應字符串是 { 「0」:{ 「0」: 「駱基」, 「1」: 「約翰」}}

我使用將Jettison作爲JSON Provider的Apache CXF Framework也使用JAXB將數據連接到低帶寬客戶端。

請注意我想將數字表示轉換爲相應的字段。

回答

1

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

以下是您如何使用EclipseLink JAXB(MOXy)註釋的Student類支持您的用例。

演示

import java.io.StringReader; 
import java.util.*; 
import javax.xml.bind.*; 

public class Demo { 

    public static void main(String[] args) throws Exception { 
     Map<String, Object> properties = new HashMap<String, Object>(1); 
     properties.put("eclipselink.media-type", "application/json"); 
     JAXBContext jc = JAXBContext.newInstance(new Class[] {Student.class}, properties); 

     Unmarshaller unmarshaller = jc.createUnmarshaller(); 
     StringReader json = new StringReader("{\"0\":{\"0\":\"Rockey\",\"1\":\"John\"}}"); 
     Student student = (Student) unmarshaller.unmarshal(json); 

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

} 

輸出

{ 
    "0" : { 
     "0" : "Rockey", 
     "1" : "John" 
    } 
} 

jaxb.properties

要使用莫西爲您的JAXB提供者,你需要包括在名爲jaxb.properties文件同樣的pac卡格與下面進入你的領域模型:

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory 

莫西和JAX-RS

對於JAX-RS應用程序,你可以利用MOXyJsonProvider類,使JSON結合(見: http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html)。

+0

但沒有一種方法轉換後返回JSON字符串。如何使用jaxB獲取json字符串 –

1

拋棄能做到這一點。發現解組JSON的樣本代碼與JAXB here到對象:

JAXBContext jc = JAXBContext.newInstance(Customer.class); 

JSONObject obj = new JSONObject("{\"customer\":{\"id\":123,\"first-name\":\"Jane\",\"last-name\":\"Doe\",\"address\":{\"street\":\"123 A Street\"},\"phone-number\":[{\"@type\":\"work\",\"$\":\"555-1111\"},{\"@type\":\"cell\",\"$\":\"555-2222\"}]}}"); 
Configuration config = new Configuration(); 
MappedNamespaceConvention con = new MappedNamespaceConvention(config); 
XMLStreamReader xmlStreamReader = new MappedXMLStreamReader(obj, con); 

Unmarshaller unmarshaller = jc.createUnmarshaller(); 
Customer customer = (Customer) unmarshaller.unmarshal(xmlStreamReader);