【问题标题】:json formatting with moshi用moshi格式化json
【发布时间】:2016-05-03 18:26:11
【问题描述】:

有没有人知道如何让 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 以保持一致性

【问题讨论】:

    标签: java json moshi


    【解决方案1】:

    如果您可以自己处理 Object 的序列化,这应该可以解决问题:

    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 中的prettyPrintObject()source code of BufferedSinkJsonWriter

    但是,如果您将 Moshi 与 Retrofit 一起使用,我还没有弄清楚是否以及如何做到这一点。

    【讨论】:

    • 谢谢!正是我搜索的内容,并认为 moshi 无法做到这一点,因为这不在这个库的范围内 - 很高兴有这种方式!
    【解决方案2】:

    现在您可以在适配器上使用.indent(" ") 方法进行格式化。

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

    【讨论】:

      猜你喜欢
      • 2019-03-25
      • 2018-05-04
      • 1970-01-01
      • 2016-09-18
      • 1970-01-01
      • 1970-01-01
      • 2021-09-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多