GSON的自定义PrintFormatting

时间:2019-01-23 12:32:41

标签: java gson

大家好!             import React, { Component, createContext } from 'react'; export const AppContext = createContext(); export class AppProvider extends Component { state = { test: '', }; getEntries() { console.log('FIRED'); this.setState({test: 'HELLO'}); } render() { return ( <AppContext.Provider value={{ ...this.state, getEntries: this.getEntries }} > {this.props.children} </AppContext.Provider> ); } } 在打印方面遇到了一些麻烦。 GSON在打印时有两个选择。

  1. 精美打印
  2. 紧凑印刷

即使documentation JsonPrintFormatter 是用于修改输出格式的类,我也打算使用经过修改的Pretty Printing形式。我在GSON存储库中找不到该类!

关于这种情况的任何想法,或者我可以修改GSON打印!? 除此之外,使用Java语言修改间距或GSON的任何库也将有所帮助。

精美打印:

formatting of JSON

紧凑打印:

    {
  "classname": "something",
  "type": "object",
  "version": 1,
  "properties": [
    {
      "propertyname": "something1",
      "type": "String",
      "length": 255
    },
    {
      "propertyname": "something2",
      "type": "Date",
      "length": 10
    }
  ]
}

我的打印样式:

{"classname":"something","type":"object","version":1,"properties":[{"propertyname":"something1","type":"String","length":255},{"propertyname":"something2","type":"Date","length":10}]}

1 个答案:

答案 0 :(得分:2)

好吧,它目前仍在进行中,但这应该可以解决仅一个数组的问题。将研究使其更稳定并能够处理更复杂的结构。

  private static String reformat(String og){
    String reformattable = og;
    String[] parts = reformattable.split("\\[",2);
    String arrayPart = parts[1];
    String arrayOnly = arrayPart.split("]",2)[0];
    reformattable = arrayOnly.replaceAll("\\{\n","{");
    reformattable = reformattable.replaceAll("\",\n", "\\\",");
    reformattable = reformattable.replaceAll(" +"," ");
    reformattable = reformattable.replaceAll("\\{ ","   {");
    reformattable = reformattable.replaceAll("\n }","}");

    return og.replace(arrayOnly,reformattable);
} 

结果应如下所示(至少对于我的简单课程而言):

{
 "classname": "test",
 "properties": [
   {"propertyname": "1", "length": 1},
   {"propertyname": "1", "length": 1}
 ]
}