从嵌套的POJOS形成Json

时间:2014-06-18 05:30:50

标签: java json pojo

我已经嵌套了POJO,如下所示。所有POJO都在同一个包装中。请注意学生名字是pojo,所有其他POJO都在里面

 class Student{

     String firstName;
     String lastName;

     List <Activities> activites;

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

    public List<Activities> getActivites() {
        return activites;
    }

    public void setActivites(List<Activities> activites) {
        this.activites = activites;
    }

    }

    class Activites{

    List<Quipments> quipments;

    String time;

    public List<Quipments> getQuipments() {
        return quipments;
    }

    public void setQuipments(List<Quipments> quipments) {
        this.quipments = quipments;
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }



    }

    class Quipments{

    String Type;

    public String getType() {
        return Type;
    }

    public void setType(String type) {
        Type = type;
    }

    }

我想在json中转换上面的学生POJO,其中包含其他pojo的所有值。

我们不打算在api下面使用。我知道下面的一个有效。

import com.sun.jersey.api.json.JSONJAXBContext;
import com.sun.jersey.api.json.JSONMarshaller;

想要使用下面的内容

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

请咨询

1 个答案:

答案 0 :(得分:0)

使用这个非常受欢迎的图书馆https://github.com/google/gson

String sample = "{firstName: \"mardar\", lastName: \"pandit\"}";
com.google.gson.Gson gson = new com.google.gson.Gson();
Student student = gson.fromJson(sample, Student.class);
System.out.println(gson.toJson(student));