Home > Blockchain >  Json string not formatted in browser but formatted in console
Json string not formatted in browser but formatted in console

Time:01-14

I am trying to output object serialized to json like this

@GetMapping("/person")
public String getPerson() throws JsonProcessingException {
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    System.out.println(mapper.writeValueAsString(person)); //just for debug
    return mapper.writeValueAsString(person);
}

I get what I wish in console:

{
  "name" : "person",
  "age" : 29,
  "listSkills" : [ "s1", "s2", "s3" ],
  "id" : 1,
  "hashCode" : 2145420209
} 

but in browser it is printed in one line and just gets different font

{ "name" : "person", "age" : 29, "listSkills" : [ "s1", "s2", "s3" ], "id" : 1, "hashCode" : 2145420209 }

CodePudding user response:

Problems

  1. You expect browser to have the same font(and colors) as console!? (Your expectations "base on wrong assumptions"/you must care)
  2. You don't use @[Rest]Controller as enter image description here

Key points

  • Using spring-boot "jacksonObjectMapper" (auto & properties config).
  • Returning the desired type and not a String.

CodePudding user response:

You can install a json formatter for your browser e.g. for Chrome this one is quite popular: JSON Formatter or you can find a similar one for your browser of choice.

Usually they come with great features such as sintax highlighting, clickable urls, toggles and some more.

CodePudding user response:

In Spring boot, the GET method will produce result with content type of application/json by default.

If you want a formatted string in browsers, set produces to text/plain, aka

@GetMapping(value = "/person", produces = MediaType.TEXT_PLAIN_VALUE)
  •  Tags:  
  • Related