Java json красивый вывод

How to pretty print JSON using Gson in Java

In this tutorial, you’ll learn how to use Gson to enable pretty print JSON output. By default, Gson outputs the final JSON in compact format:

try  // create user object User user = new User("John Doe", "john.doe@example.com", new String[]"Member", "Admin">, true); // convert user object to JSON String json = new Gson().toJson(user); // print JSON string System.out.println(json); > catch (Exception ex)  ex.printStackTrace(); > 

The above code will generate the following compact-print JSON:

"name":"John Doe","email":"john.doe@example.com","roles":["Member","Admin"],"admin":true> 

To enable JSON pretty-print, you need the Gson object using GsonBuilder and call the setPrettyPrinting() method, as shown below:

try  // create user object User user = new User("John Doe", "john.doe@example.com", new String[]"Member", "Admin">, true); // create a Gson instance with pretty-printing Gson gson = new GsonBuilder().setPrettyPrinting().create(); // convert user object to pretty print JSON String json = gson.toJson(user); // print JSON string System.out.println(json); > catch (Exception ex)  ex.printStackTrace(); > 

Now here is what the final pretty-print JSON looks like:

 "name": "John Doe", "email": "john.doe@example.com", "roles": [ "Member", "Admin" ], "admin": true > 

For more Gson examples, check out the How to read and write JSON using Gson in Java tutorial.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like.

Источник

Jackson: красивое форматирование

В данном руководстве мы рассмотрим возможности библиотеки Jackson в части «красивого» (удобного для восприятия) оформления JSON объектов при выводе их в строку и на консоль.

Красивое оформление JSON объектов

Рассмотрим способ преобразования JSON объекта в строковое представление:

ObjectMapper mapper = new ObjectMapper(); try < Mapmap = mapper.readValue(new File(FILENAME), new TypeReference()<>); System.out.println(mapper.writeValueAsString(map)); > catch (IOException ex)

В результате будет получена строка следующего вида:

Для того чтобы строковое представление JSON объекта имело удобный для восприятия человеком вид, необходимо использовать метод writerWithDefaultPrettyPrinter :

ObjectMapper mapper = new ObjectMapper(); try < Mapmap = mapper.readValue(new File(FILENAME), new TypeReference()<>); System.out.println(mapper.writerWithDefaultPrettyPrinter() .writeValueAsString(map)); > catch (IOException ex)

Красивое оформление JSON строки

Аналогичным образом можно форматировать и JSON строки.

Рассмотрим пример вывода JSON строки на стандартный вывод:

ObjectMapper mapper = new ObjectMapper(); try < String JSON_STRING = "<"age":2,"name":"j4web","messages":["msg 1","msg 2","msg 3"]>«; System.out.println(mapper.writerWithDefaultPrettyPrinter() .writeValueAsString(JSON_STRING)); > catch (IOException ex)

Для того, чтобы вывод JSON строки был в удобном виде, прежде чем выводить эту строку на стандартный вывод, можно перевести ее в JSON объект и только потом выводить его строковое представление с помощью метода writerWithDefaultPrettyPrinter :

ObjectMapper mapper = new ObjectMapper(); try < String JSON_STRING = "<"age":2,"name":"j4web","messages":["msg 1","msg 2","msg 3"]>«; Object jsonObject = mapper.readValue(JSON_STRING, Object.class); System.out.println(mapper.writerWithDefaultPrettyPrinter() .writeValueAsString(jsonObject)); > catch (IOException ex)

Полезная информация

Источник

Красивое форматирование в Gson

В этой статье мы рассмотрим способ «человеческого» оформления JSON при использовании библиотеки Google Gson. В качестве основы возьмем пример с моделью данных и преобразования Java объектов в JSON.

Если применять стандартный подход к формированию JSON данных:

Gson gson = new Gson(); String json = gson.toJson(map); System.out.println(json);

То результат будет следующий:

Для того, чтобы JSON текст был отформатирован в удобном для восприятии человеком виде, нужно использовать класс GsonBuilder и его метод setPrettyPrinting() :

Gson gson = new GsonBuilder().setPrettyPrinting().create(); String json = gson.toJson(map); System.out.println(json);

И результат в этом случае будет иметь вид:

Полный исходный код примера использования класса GsonBuilder и метода setPrettyPrinting() для получения «красивого» JSON-а:

package ru.j4web.examples.java.json.gsonprettyprintexample; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class GsonPrettyPrintExample < public static void main(String[] args) < Mapmap = new HashMap<>(); map.put("name", "j4web"); map.put("site", "https://j4web.ru"); map.put("age", 2); List messages = new ArrayList<>(); messages.add("Message 1"); messages.add("Message 2"); messages.add("Message 3"); map.put("messages", messages); Gson gson = new GsonBuilder().setPrettyPrinting().create(); String json = gson.toJson(map); System.out.println(json); > >

Полезная информация

Источник

Pretty-Printing JSON with Jackson in Java and Spring Boot

Jackson is one of the most common libraries for working with serialization and deserialization in Java and Spring Boot, primarily used for parsing and converting between POJOs and JSON.

Though, if you’ve worked with Jackson, you’ll notice a distinct lack of pretty-printing by default:

In this short tutorial, you’ll learn how to pretty-print JSON with Jackson in standard Java and with Spring Boot.

We’ll be working with a JSON string, and a POJO converted into a JSON string, since these behave differently:

public class Book < private String title; private String author; private int releaseYear; public Book(String title, String author, int releaseYear) < this.title = title; this.author = author; this.releaseYear = releaseYear; > // Getters, setters, toString(), . 

Let’s instantiate a Book instance, and a string for the input:

String inputString = " + "\"Task 1\" : \"In_Progress\",\n" + "\"Task 2\" : \"Done\",\n" + "\"Task 3\" : \"Planned\"\n" + ">"; Book book = new Book("Our Mathematical Universe", "Max Tegmark", 2014); 

Pretty-Print JSON with Jackson Once

If you’d like to simply pretty-print once, in a single call, rather than setting the global printing flag — you can simply use the writerWithDefaultPrettyPrinter() call before writing a value as a string:

ObjectMapper mapper = new ObjectMapper(); Object jsonString = mapper.readValue(inputString, Object.class); String indentedString = mapper.writerWithDefaultPrettyPrinter() .writeValueAsString(jsonString); System.out.println(jsonString); System.out.println(indentedString); 

The input string was read from (JSON-to-Object), and the value of this object was written back into a string, using pretty-printing (Object-to-JSON):

Alternatively, when using readTree() , the resulting JsonNode has a toPrettyString() function that serves as a great simple way to convert strings to pretty-printed JSON:

ObjectMapper mapper = new ObjectMapper(); Object jsonString = mapper.readTree(inputString).toPrettyString(); System.out.println(jsonString); 

This is a quick and simple way to format an input JSON string! When working with POJOs, instead of reading from a given input, we’ll only perform Object-to-JSON conversion and enable pretty-printing:

ObjectMapper mapper = new ObjectMapper(); String jsonBook = mapper.writeValueAsString(book); String indentedBook = mapper.writerWithDefaultPrettyPrinter() .writeValueAsString(book); System.out.println(jsonBook); System.out.println(indentedBook); 

Global Pretty-Print Setting

Alternatively, you can enable global pretty-printing, if that’s the preferable global behavior of Jackson for your project. This is as easy as using the enable() method of the ObjectMapper() instance when you’re instantiating it:

ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT); 

As soon as you write an object as a JSON string — pretty-printing will be enabled by default:

Object jsonString = mapper.readValue(inputString, Object.class); String indentedString = mapper.writeValueAsString(jsonString); System.out.println(jsonString); System.out.println(indentedString); 
String jsonBook = mapper.writeValueAsString(book); System.out.println(jsonBook); 

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

This approach is significantly less verbose if pretty-printing is a common display format.

Pretty-Printing Jackson with Spring Boot

If you’re using Spring Boot, without a manual ObjectMapper instance being created and rely on the underlying serializer, you can set the indent_output flag to true in the application.properties file:

spring.jackson.serialization.indent_output=true 
spring: jackson: serialization: INDENT_OUTPUT: true 

This sets the SerializationFeature.INDENT_OUTPUT flag in Spring’s ObjectMapper instance.

Conclusion

In this short tutorial, we’ve taken a look at how you can pretty-print JSON from a String or POJO using Jackson. We’ve explored single-print changes (when you only want to pretty-print once) and setting the global Jackson flag for ObjectMapper . Finally, we took a look at changing Spring Boot properties for enabling pretty printing with Jackson.

Источник

How to pretty print JSON using Jackson in Java

In this short article, you’ll learn how to use Jackson to enable pretty print JSON output.

By default, Jackson outputs the final JSON in the compact format:

try  // create user object User user = new User("John Doe", "john.doe@example.com", new String[]"Member", "Admin">, true); // convert user object to JSON String json = new ObjectMapper().writeValueAsString(user); // print JSON string System.out.println(json); > catch (Exception ex)  ex.printStackTrace(); > 

Here is what the generated JSON looks like:

"name":"John Doe","email":"john.doe@example.com","roles":["Member","Admin"],"admin":true> 

To enable the pretty print JSON output while serializing a Java Object, you can use the writerWithDefaultPrettyPrinter() method of ObjectMapper :

try  // create user object User user = new User("John Doe", "john.doe@example.com", new String[]"Member", "Admin">, true); // create object mapper instance ObjectMapper mapper = new ObjectMapper(); // convert user object to pretty print JSON String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(user); // print JSON string System.out.println(json); > catch (Exception ex)  ex.printStackTrace(); > 

Now here is what the final pretty print JSON looks like:

 "name" : "John Doe", "email" : "john.doe@example.com", "roles" : [ "Member", "Admin" ], "admin" : true > 

You can also enable the pretty print JSON output globally by using the DefaultPrettyPrinter class, as shown below:

try  // create user object User user = new User("John Doe", "john.doe@example.com", new String[]"Member", "Admin">, true); // create object mapper instance ObjectMapper mapper = new ObjectMapper(); // create an instance of DefaultPrettyPrinter ObjectWriter writer = mapper.writer(new DefaultPrettyPrinter()); // convert user object to pretty print JSON String json = writer.writeValueAsString(user); // print JSON string System.out.println(json); > catch (Exception ex)  ex.printStackTrace(); > 

For more Jackson examples, check out the how to read and write JSON using Jackson in Java tutorial.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like.

Источник

Читайте также:  Import try catch java
Оцените статью