简体   繁体   English

Json - Java对象到Json

[英]Json - Java Object to Json

I am very new to Json and my goal to create the Json output below from Java bean. 我是Json的新手,我的目标是从Java bean创建下面的Json输出。 How should I structure my Java object? 我应该如何构建我的Java对象? Should I have MyResult class and User and Result as subclasses? 我应该将MyResult类和User和Result作为子类吗? What Json library can I use for this? 我可以使用什么Json库?

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

Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-222) expert group. 注意:我是EclipseLink JAXB(MOXy)的负责人,也是JAXB(JSR-222)专家组的成员。


How should I structure my Java object? 我应该如何构建我的Java对象?

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. MOXy的JSON绑定利用JAXB注释将域模型映射到JSON,所以我也包含了这些注释。 JAXB implementations have default rules for mapping field/property names, but since your document differs from the default each field had to be annotated. JAXB实现具有映射字段/属性名称的默认规则,但由于您的文档与默认值不同,因此必须对每个字段进行注释。

MyResult 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? 我可以使用什么Json库?

Below is how you can use MOXy to do the JSON binding: 下面是如何使用MOXy进行JSON绑定:

jaxb.properties 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: 要将MOXy用作JAXB提供程序,您需要在域模型所在的包中包含一个名为jaxb.properties的文件, jaxb.properties包含以下条目:

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

Demo 演示

Note how MOXy's JSON binding does not require any compile time dependencies. 注意MOXy的JSON绑定如何不需要任何编译时依赖性。 All the necessary APIs are available in Java SE 6. You can add the necessary supporting APIs if you are using Java SE 5. 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);
    }

}

input.json/Output input.json /输出

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

Googles GSON is a really nice json lib. 谷歌GSON是一个非常好的json lib。 This is from the previous link and it basically outlines some of its functionality. 来自之前的链接,它基本上概述了它的一些功能。

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

Although closed, this SO post can help you understand the differences between Jackson and GSON. 虽然已关闭,但这篇SO帖子可以帮助您了解Jackson和GSON之间的差异。 Which one is "best" depends on what is important for you. 哪一个是“最好的”取决于对您来说重要的一个。

EDIT: Specifically for Jackson, your example looks a lot like the example they give for what they call Full Data Binding, you can read it here . 编辑:特别是杰克逊,你的例子看起来很像他们所谓的全数据绑定的例子,你可以在这里阅读。 Btw, although the announced 5 minutes needed to read that document is maybe a bit short, it gives a complete overview of the different ways Jackson can be used. 顺便说一句,虽然宣布5分钟需要阅读该文件可能有点短,但它提供了杰克逊可以使用的不同方式的完整概述。 You'll also notice that the examples given do not use annotations. 您还会注意到给出的示例不使用注释。

Or GSON 或者GSON

Super easy (no getters/settres, no annotations or configurations needed). 超级简单(无需getter / settres,无需注释或配置)。

class BagOfPrimitives {
  private int value1 = 1;
  private String value2 = "abc";
  private transient int value3 = 3;
}

BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj); 

==> json is {"value1":1,"value2":"abc"}

What Json library can I use for this? 我可以使用什么Json库? Jackson Library is used to serialize Java objects into JSON and deserialize JSON string into Java objects. Jackson Library用于将Java对象序列化为JSON,并将JSON字符串反序列化为Java对象。 Add the following dependencies to pom.xml. 将以下依赖项添加到pom.xml。

   <dependency>
     <groupId>com.fasterxml.jackson.core</groupId>
     <artifactId>jackson-databind</artifactId>
     <version>2.9.4</version> 
     </dependency>

This dependency will transitively add the following libraries to the classpath: jackson-annotations-2.9.4.jar jackson-core-2.9.4.jar jackson-databind-2.9.4.jar 这种依赖关系会将以下库传递给类路径:jackson-annotations-2.9.4.jar jackson-core-2.9.4.jar jackson-databind-2.9.4.jar

**Note: Please always go with the latest jars. **注意:请随时使用最新的罐子。

How should I structure my Java object? 我应该如何构建我的Java对象? Please see the full working code. 请参阅完整的工作代码。

  **MainClass.java:**

      import java.io.IOException;

     import com.fasterxml.jackson.databind.ObjectMapper;
     import com.fasterxml.jackson.databind.SerializationFeature;

    public class MainClass {

    public static void main(String[] args) throws IOException {

    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.INDENT_OUTPUT);

    Result result = new Result();
    result.setCourse("blah");
    result.setScore("10.0");

    User user = new User();
    user.setName("blah blah");
    user.setEmail("blah@blah.com");

    MyResult myResult = new MyResult();
    myResult.setAccountID("12345");
    myResult.setResult(result);
    myResult.setUser(user);

    MyPojo myPojo = new MyPojo();
    myPojo.setMyResult(myResult);

    String jsonStr = mapper.writeValueAsString(myPojo);

    System.out.println(jsonStr);

} }

     **MyPojo.java:-**


    import com.fasterxml.jackson.annotation.JsonProperty;
    import com.fasterxml.jackson.annotation.JsonPropertyOrder;

@JsonPropertyOrder({ "AccountID", "User", "Result" })
public class MyPojo {
private MyResult MyResult;

public MyResult getMyResult() {
    return MyResult;
}

@JsonProperty("MyResult")
public void setMyResult(MyResult MyResult) {
    this.MyResult = MyResult;
} }


    **MyResult.java:**

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

@JsonPropertyOrder({ "AccountID", "User", "Result" })
public class MyResult {

private User User;

private Result Result;

private String AccountID;

public User getUser() {
    return User;
}

@JsonProperty("User")
public void setUser(User User) {
    this.User = User;
}

public Result getResult() {
    return Result;
}

@JsonProperty("Result")
public void setResult(Result Result) {
    this.Result = Result;
}

public String getAccountID() {
    return AccountID;
}

  @JsonProperty("AccountID")
  public void setAccountID(String AccountID) {
    this.AccountID = AccountID;
    } }


    **Result.java:**

 import com.fasterxml.jackson.annotation.JsonProperty;
 import com.fasterxml.jackson.annotation.JsonPropertyOrder;

   @JsonPropertyOrder({ "Course", "Score" })
    public class Result {

    private String Course;

    private String Score;

    public String getCourse() {
    return Course;
    }

    @JsonProperty("Course")
    public void setCourse(String Course) {
    this.Course = Course;
}

   public String getScore() {
    return Score;
}

   @JsonProperty("Score")
  public void setScore(String Score) {
    this.Score = Score;
  } }


    **User.java:**

    import com.fasterxml.jackson.annotation.JsonProperty;
    import com.fasterxml.jackson.annotation.JsonPropertyOrder;

    @JsonPropertyOrder({ "Name", "Email" })
      public class User {

    private String Name;

    private String Email;

    public String getName() {
    return Name;
    }

@JsonProperty("Name")
public void setName(String Name) {
    this.Name = Name;
}

public String getEmail() {
    return Email;
}

@JsonProperty("Email")
public void setEmail(String Email) {
    this.Email = Email;
}

@Override
public String toString() {
    return "ClassPojo [Name = " + Name + ", Email = " + Email + "]";
} }

   **Result:**

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

Note: Please note the use of Json Annotations like @JsonProperty("Email") to make json property names as same in the expected output & @JsonPropertyOrder({ "Name", "Email" } to maintain the sequence as in expected output. Refer: https://www.baeldung.com/jackson-annotations . 注意:请注意使用Json Annotations(如@JsonProperty(“Email”))使json属性名称在预期输出中与@JsonPropertyOrder({“Name”,“Email”}相同,以保持序列与预期输出一样。请参阅: https//www.baeldung.com/jackson-annotations

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM