Formatting json with moshi

Does anyone know a way to get moshi to create multi-line indented json (for human consumption in the context of config.json) so from:

{"max_additional_random_time_between_checks":180,"min_time_between_checks":60} 

like that:

 { "max_additional_random_time_between_checks":180, "min_time_between_checks":60 } 

I know other json-writer implementations can do this - but I would like to stick with moshi here for consistency

+5
source share
2 answers

If you can handle serializing the object yourself, this should do the trick:

 import com.squareup.moshi.JsonWriter; import com.squareup.moshi.Moshi; import java.io.IOException; import okio.Buffer; public class MoshiPrettyPrintingTest { private static class Dude { public final String firstName = "Jeff"; public final String lastName = "Lebowski"; } public static void main(String[] args) throws IOException { final Moshi moshi = new Moshi.Builder().build(); final Buffer buffer = new Buffer(); final JsonWriter jsonWriter = JsonWriter.of(buffer); // This is the important part: // - by default this is `null`, resulting in no pretty printing // - setting it to some value, will indent each level with this String // NOTE: You should probably only use whitespace here... jsonWriter.setIndent(" "); moshi.adapter(Dude.class).toJson(jsonWriter, new Dude()); final String json = buffer.readUtf8(); System.out.println(json); } } 

Fingerprints:

 { "firstName": "Jeff", "lastName": "Lebowski" } 

See prettyPrintObject() for this test file and source code for BufferedSinkJsonWriter .

However, I still do not understand whether and how to do this if you are using Moshi with refinement.

+3
source

Now you can use the .indent(" ") method for the adapter for formatting.

  final Moshi moshi = new Moshi.Builder().build(); String json = moshi.adapter(Dude.class).indent(" ").toJson(new Dude()) 
+4
source

Source: https://habr.com/ru/post/1241562/


All Articles