且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Json - Java 对象转 Json

更新时间:2023-01-16 21:29:22

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


How should I structure my Java object?

Below is what your object model could look like. MOXy's JSON binding leverages JAXB annotations for mapping the domain model to JSON, so I have included those as well. JAXB implementations have default rules for mapping field/property names, but since your document differs from the default each field had to be annotated.

MyResult

package forum11001458;

import javax.xml.bind.annotation.*;

@XmlRootElement(name="MyResult")
public class MyResult {

    @XmlElement(name="AccountID")
    private String accountID;

    @XmlElement(name="User")
    private User user;

    @XmlElement(name="Result")
    private Result result;

}

User

package forum11001458;

import javax.xml.bind.annotation.XmlElement;

public class User {

    @XmlElement(name="Name")
    private String name;

    @XmlElement(name="Email")
    private String email;

}

Result

package forum11001458;

import javax.xml.bind.annotation.XmlElement;

public class Result {

    @XmlElement(name="Course")
    private String course;

    @XmlElement(name="Score")
    private String score;

}


What Json library can I use for this?

Below is how you can use MOXy to do the JSON binding:

jaxb.properties

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

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

Demo

Note how MOXy's JSON binding does not require any compile time dependencies. All the necessary APIs are available in Java SE 6. You can add the necessary supporting APIs if you are using Java SE 5.

package forum11001458;

import java.io.File;
import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(MyResult.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        unmarshaller.setProperty("eclipselink.media-type", "application/json");
        File json = new File("src/forum11001458/input.json");
        Object myResult = unmarshaller.unmarshal(json);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty("eclipselink.media-type", "application/json");
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(myResult, System.out);
    }

}

input.json/Output

{
   "MyResult" : {
      "AccountID" : "12345",
      "User" : {
         "Name" : "blah blah",
         "Email" : "blah@blah.com"
      },
      "Result" : {
         "Course" : "blah",
         "Score" : "10.0"
      }
   }
}