我正在使用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 Response String是 { “0”:{ “0”: “骆基”, “1”: “约翰”}}
我正在使用Apache CXF Framework和Jettison,因为JSON Provider也使用JAXB将数据连接到低带宽客户端。
请注意我想将数字表示转换为相应的字段。
答案 0 :(得分:2)
您可以参考Google-GSON库 - https://github.com/google/gson
您还可以参考之前的stackoverflow答案 - Convert a JSON string to object in Java ME?
答案 1 :(得分:1)
Jettison可以做到这一点。找到了一个使用JAXB here解组JSON到对象的示例代码:
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);
答案 2 :(得分:0)
注意:我是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 强>
要将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)。