Maison  >  Article  >  Java  >  Comment imprimer joliment du JSON à l'aide de la bibliothèque Gson en Java ?

Comment imprimer joliment du JSON à l'aide de la bibliothèque Gson en Java ?

PHPz
PHPzavant
2023-09-13 21:05:111312parcourir

Comment imprimer joliment du JSON à laide de la bibliothèque Gson en Java ?

Gson est une bibliothèque Java JSON créée par Google. En utilisant Gson, nous pouvons générer du JSON et convertir du JSON en objets Java. Par défaut, Gson peut imprimer JSON au format compact. Pour activer Gson Pretty Printing, nous devons configurer une instance Gson à l'aide de la méthode setPrettyPrinting() de la classe GsonBuilder, qui configure Gson pour qu'il génère un ajustement JSON à la page pour une jolie impression.

Syntaxe

public GsonBuilder setPrettyPrinting()

Exemple

import java.util.*;
import com.google.gson.*;
public class PrettyJSONTest {
   public static void main( String[] args ) {
      Employee emp = new Employee("Raja", "115", "Content Engineer", "Java", "Hyderabad");
      Gson gson = new GsonBuilder().setPrettyPrinting().create(); // pretty print
      String prettyJson = gson.toJson(emp);
      System.out.println(prettyJson);
   }
}
// Employee class
class Employee {
   private String name, id, designation, technology, location;
   public Employee(String name, String id, String designation, String technology, String location) {
      super();
      this.name = name;
      this.id = id;
      this.designation = designation;
      this.technology = technology;
      this.location = location;
   }
   public String getName() {
      return name;
   }
   public String getId() {
      return id;
   }
   public String getDesignation() {
      return designation;
   }
   public String getTechnology() {
      return technology;
   }
   public String getLocation() {
      return location;
   }
}

Sortie

{
 "name": "Raja",
 "id": "115",
 "designation": "Content Engineer",
 "technology": "Java",
 "location": "Hyderabad"
}

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Cet article est reproduit dans:. en cas de violation, veuillez contacter admin@php.cn Supprimer