Home > database >  Kotlin: JSON string with linebreaker and variable
Kotlin: JSON string with linebreaker and variable

Time:02-03

I would like to add linebreakers to a JSON string so it will be more readable.

val myString = "some string"
val myObjectJson = `
{
    "example1": "value",
    "example2": $myString
}`

So later I can use ObjectMapper to create an object. objectMapper.readValue(myObjectJson, MyClass::class.Java)

What I'm trying to figure out:

  1. How to add lineBreaker in Json string?

Tried template literals:"`", doesn't seem to work in Kotline. gives Expecting an expression error.

  1. How to use variable in Json string? This might go away after I figure out how to add linebreakers.

CodePudding user response:

(Edited because I think I have misunderstood your question).

Are you asking how to lay out a JSON string in the source code? If so then what you are looking for is the Raw String feature implemented with 3 double-quotes like this:

val myObjectJson = """
{
    "example1": "value",
    "example2": $myString
}
"""

But in case you asking

How to add lineBreaker in Json string?

(Assuming you are using Jackson's ObjectMapper)

  1. Simply use writerWithDefaultPrettyPrinter() like this: MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(value)
  2. If that is not good enough for you I suppose you could implement a custom Pretty Printer: https://www.javadoc.io/static/com.fasterxml.jackson.core/jackson-core/2.14.2/com/fasterxml/jackson/core/PrettyPrinter.html
  • Related