Json - Java对象到Json

use*_*021 6 java json java-ee

我是Json的新手,我的目标是从Java bean创建下面的Json输出.我应该如何构建我的Java对象?我应该将MyResult类和User和Result作为子类吗?我可以使用什么Json库?

“MyResult” {
    “AccountID”: “12345”,
    "User" {
        "Name": "blah blah",
        "Email": “blah@blah.com”,
     },
     "Result" {
         "Course": “blah”,
         "Score": “10.0”
     }
 }
Run Code Online (Sandbox Code Playgroud)

bdo*_*han 9

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


我应该如何构建我的Java对象?

以下是您的对象模型的外观.MOXy的JSON绑定利用JAXB注释将域模型映射到JSON,所以我也包含了这些注释.JAXB实现具有映射字段/属性名称的默认规则,但由于您的文档与默认值不同,因此必须对每个字段进行注释.

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;

}
Run Code Online (Sandbox Code Playgroud)

用户

package forum11001458;

import javax.xml.bind.annotation.XmlElement;

public class User {

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

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

}
Run Code Online (Sandbox Code Playgroud)

结果

package forum11001458;

import javax.xml.bind.annotation.XmlElement;

public class Result {

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

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

}
Run Code Online (Sandbox Code Playgroud)

我可以使用什么Json库?

下面是如何使用MOXy进行JSON绑定:

jaxb.properties

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

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
Run Code Online (Sandbox Code Playgroud)

演示

注意MOXy的JSON绑定如何不需要任何编译时依赖性.Java SE 6中提供了所有必需的API.如果您使用的是Java SE 5,则可以添加必要的支持API.

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

}
Run Code Online (Sandbox Code Playgroud)

input.json /输出

{
   "MyResult" : {
      "AccountID" : "12345",
      "User" : {
         "Name" : "blah blah",
         "Email" : "blah@blah.com"
      },
      "Result" : {
         "Course" : "blah",
         "Score" : "10.0"
      }
   }
}
Run Code Online (Sandbox Code Playgroud)


Joh*_*ane 7

谷歌GSON是一个非常好的json lib.来自之前的链接,它基本上概述了它的一些功能.


Chu*_*Mah 5

杰克逊也非常快速且易于使用