0

I am writing a object to JSON file. Want to know how can I add parent element in object OR just add parent element in JSON file.

    public void writeToJSON(Path dest, Student studentJSON) throws IOException {
        Gson gson = new GsonBuilder().serializeNulls().setPrettyPrinting().create();
        try (PrintWriter wr = new PrintWriter(Files.newBufferedWriter(dest))) {
        gson.toJson(studentJSON, wr);
    }

This produces student list in Json as

{
    "students": [
          {
            "Name": "foo",
            "Grade": "A"
          },
          {
            "Name": "bar",
            "Grade": "B+",
          }
    ]
}

I am looking for a JSON like this :

{
    "class" : {
        "students": [
              {
                "Name": "foo",
                "Grade": "A"
              },
              {
                "Name": "bar",
                "Grade": "B+",
              }
        ]
    }
}

I don't want to create an additional class for this. Any idea how can I change my write function or if GSON provides any property for this ?

1
  • 1
    What is the reason you don't want to create new class? Commented May 8, 2020 at 15:47

1 Answer 1

1

You have to modify you method to look like this

public static void writeToJSON(Path dest, List<Student> studentJSON) throws IOException {
        Gson gson = new GsonBuilder().serializeNulls().setPrettyPrinting().create();
        try (PrintWriter wr = new PrintWriter(Files.newBufferedWriter(dest))) {
            JsonElement jsonElement = gson.toJsonTree(studentJSON);
            JsonObject classObject = new JsonObject();
            JsonObject studentsObject = new JsonObject();
            studentsObject.add("students", jsonElement);
            classObject.add("class", studentsObject);
            gson.toJson(classObject, wr);
        }
    }

Student POJO class

class Student {
        public Student(String name, String grade) {
            this.name = name;
            this.grade = grade;
        }

        @SerializedName("Name")
        String name;
        @SerializedName("Grade")
        String grade;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getGrade() {
            return grade;
        }

        public void setGrade(String grade) {
            this.grade = grade;
        }
    }

This is how would you class it fo

List<Student> students = new ArrayList<>();
students.add(new Student("silentsudo", "A+"));
students.add(new Student("random", "C+"));
writeToJSON(Paths.get("/home/usertest.json"), students);

Explanation:

  • Create Json object for class.
  • Create json Object for student.
  • Compose students JsonElement using string.
  • Put students in studentJosn Object
  • Put student jsonObject into class
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @silentsudo for responding. What if I have List<Student> in POJO class ?
your initial question was not to use class, and i asked what is stopping for use that, if you use a pojo class is will work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.