Java – JSON and Moshi formatting
•
Java
Does anyone know how to make Moshi generate multiline JSON with indentation (for human use in the context of config. JSON)
{"max_additional_random_time_between_checks":180,"min_time_between_checks":60}
Such things:
{ "max_additional_random_time_between_checks":180,"min_time_between_checks":60 }
I know that other JSON writer implementations can do this – but I want to stick with Moshi here for consistency
Solution
If you can handle serialized objects yourself, this should solve the problem:
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); } }
This print:
{ "firstName": "Jeff","lastName": "Lebowski" }
See prettyprintobject() in this test file and source code of bufferedsinkjsonwriter
However, if you use Moshi and retrofit, I haven't figured out whether and how to do it
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码