小编典典

JSON字符串到对象的映射

json

我有一个JSON响应,我需要将对应的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”:“ Rockey”,“ 1”:“ John”}}

我将Apache CXF Framework与Jettison一起使用,因为JSON Provider还使用JAXB将数据连接到低带宽客户端。

请注意,我要将数字表示形式转换为相应的字段。


阅读 314

收藏
2020-07-27

共1个答案

小编典典

注意: 我是 EclipseLink
JAXB(MOXy)的
负责人,并且是
JAXB(JSR-222)
专家组的成员。

下面是如何Student用EclipseLink JAXB(MOXy)注释的类的用例支持。

演示版

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

要将MOXy用作JAXB提供程序,您需要jaxb.properties在与域模型相同的包中包含一个名为的文件,并带有以下条目:

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

MOXy和JAX-RS

对于JAX-
RS应用程序,您可以利用MOXyJsonProvider该类来启用JSON绑定(请参阅:http : //blog.bdoughan.com/2011/05/specifying-
eclipselink-moxy-as-your.html)。

2020-07-27