English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
com.google.gson.JSonElement éléments représentés par la classede Json. Nous pouvons utiliserGson de classetoJsonTree() La méthode sérialise la représentation d'un objet en un arbre de JsonElements. Nous pouvons ajouter/En ajoutant une propriété supplémentaire, sous forme de chaîne JSONgetAsJsonObject()de méthodeJSonElement. Ce méthode retourne pour transformer les éléments enJsonObjectObtenir.
public JsonObject getAsJsonObject()
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("Chaîne JSON : " + jsonStr); JsonElement jsonElement = gson.toJsonTree(student); jsonElement.getAsJsonObject().addProperty("id", ""115"); jsonStr = gson.toJson(jsonElement); System.out.println("Chaîne JSON après insertion de la propriété supplémentaire : " + jsonStr); } }// Classe Student classclass Student { private String name; public Student(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
Résultat de la sortie
Chaîne JSON : { "name": "Adithya" } Chaîne JSON après insertion de la propriété supplémentaire : { "name": "Adithya", "id": ""115" }