java – json与moshi格式化
发布时间:2020-12-14 05:53:07 所属栏目:Java 来源:网络整理
导读:有没有人知道如何让moshi生成带缩进的多行json(在config.json的上下文中供人类使用) 所以来自: {"max_additional_random_time_between_checks":180,"min_time_between_checks":60} 这样的事情: { "max_additional_random_time_between_checks":180,"min_ti
有没有人知道如何让moshi生成带缩进的多行json(在config.json的上下文中供人类使用)
所以来自: {"max_additional_random_time_between_checks":180,"min_time_between_checks":60} 这样的事情: { "max_additional_random_time_between_checks":180,"min_time_between_checks":60 } 我知道其他json-writer实现可以这样做 – 但我想在这里坚持moshi以保持一致性 解决方法
如果你可以自己处理序列化对象,这应该可以解决问题:
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); } } 这打印: { "firstName": "Jeff","lastName": "Lebowski" } 请参阅this test file和source code of 但是,如果你使用Moshi和Retrofit,我还没有弄清楚是否以及如何做到这一点. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |