
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Add Additional Property to JSON String Using Gson in Java
The com.google.gson.JSonElement class represents an element of Json. We can use the toJsonTree() method of Gson class to serialize an object's representation as a tree of JsonElements. We can add/ insert an additional property to JSON string by using the getAsJsonObject() method of JSonElement. This method returns to get the element as JsonObject.
Syntax
public JsonObject getAsJsonObject()
Example
import com.google.gson.*; public class AddPropertyGsonTest { public static void main(String[] args) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); // pretty print JSON Student student = new Student("Adithya"); String jsonStr = gson.toJson(student, Student.class); System.out.println("JSON String: \n" + jsonStr); JsonElement jsonElement = gson.toJsonTree(student); jsonElement.getAsJsonObject().addProperty("id", "115"); jsonStr = gson.toJson(jsonElement); System.out.println("JSON String after inserting additional property: \n" + jsonStr); } } // Student class class Student { private String name; public Student(String name) { this.name= name; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
Output
JSON String: { "name": "Adithya" } JSON String after inserting additional property: { "name": "Adithya", "id": "115" }
Advertisements