Moshi: How to print pretty json with moshi?

Created on 24 Apr 2017  路  2Comments  路  Source: square/moshi

How to print pretty json for a json string with moshi ?
For example:

String json = "{ \"key1\": \"value1\", \"key2\": \"value2\"}";

Output:
```json
{
"key1": "value1",
"key2": "value2"
}

Most helpful comment

Does JsonWriter.setIndent (or via JsonAdapter.indent) do what you want?
For that exact example, maybe something like the following would work to get you get you started.

String json = "{ \"key1\": \"value1\", \"key2\": \"value2\"}";
Buffer source = new Buffer().writeUtf8(json);
JsonReader reader = JsonReader.of(source);
Object value = reader.readJsonValue();
JsonAdapter<Object> adapter = new Moshi.Builder().build().adapter(Object.class).indent("    ");
String result = adapter.toJson(value);
System.out.println(result);

All 2 comments

Does JsonWriter.setIndent (or via JsonAdapter.indent) do what you want?
For that exact example, maybe something like the following would work to get you get you started.

String json = "{ \"key1\": \"value1\", \"key2\": \"value2\"}";
Buffer source = new Buffer().writeUtf8(json);
JsonReader reader = JsonReader.of(source);
Object value = reader.readJsonValue();
JsonAdapter<Object> adapter = new Moshi.Builder().build().adapter(Object.class).indent("    ");
String result = adapter.toJson(value);
System.out.println(result);

@NightlyNexus Yes, thank you.

Was this page helpful?
0 / 5 - 0 ratings