How to write Object as human readable text file

后端 未结 5 1876
无人及你
无人及你 2020-12-21 08:35

I want to write objects in human readable form in a text file, the file gets saved as a normal serialized object with unwanted characters instead.

How do I rewrite t

5条回答
  •  有刺的猬
    2020-12-21 09:19

    Two easy options:

    • ReflectionToStringBuilder from commons-lang

    in your code:

    ReflectionToStringBuilder.toString(javabook, ToStringStyle.MULTI_LINE_STYLE);
    

    will produce:

    org.marmots.application.generator.Book@77459877[
      name=Java unleashed
      author=someone
      nop=1032
      price=450
      discount=10
    ]
    

    that's nice for debugging. If you have only simple fields it will be enough; if you reference another bean inside it (and another, and another...), it will print its toString() method, so you can override toString method for all your value/transfer objects with this code in order to have nice reading methods for all).

    what I do usually is to extend from a base bean class:

    import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
    import org.apache.commons.lang3.builder.ToStringStyle;
    
    public abstract class ToStringReadable {
      @Override
      public String toString() {
        return ReflectionToStringBuilder.toString(this, ToStringStyle.MULTI_LINE_STYLE);
      }
    }
    

    extending ToStringReadable will make all your beans human readable for debugging purposes.

    • Jackson's ObjectMapper

    In your code (note that you will have to publish your attributes with getter/setter(s), it's a good practice so even better):

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.writeValue(new File("target/javabook.json"), javabook);
    

    It will produce human-readable output also, in this case JSON:

    {"name":"Java unleashed","author":"someone","nop":1032,"price":450}
    

    Using JSON approach you don't need to override toString methods as it will print all your fields but it's heavier in terms of performance, so for debugging use first method.

    Hope this helps,

提交回复
热议问题