JSON String to Object Mapping

余生长醉 提交于 2019-11-29 11:38:14

Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-222) expert group.

Below is how you an support your use case with your Student class as annotated with EclipseLink JAXB (MOXy).

Demo

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);
    }

}

Output

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

jaxb.properties

To use MOXy as your JAXB provider you need to include a file called jaxb.properties in the same package as your domain model with the following entry:

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

MOXy and JAX-RS

For JAX-RS applications you can leverage the MOXyJsonProvider class to enable JSON-binding (see: http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html).

Yashpal Singla

You can refer Google-GSON library - https://github.com/google/gson

You can also refer earlier stackoverflow answer - Convert a JSON string to object in Java ME?

Jettison could do this. Found a sample code of unmarshalling JSON to object with 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);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!