Evgeny Mamaev
Evgeny Mamaev

Reputation: 1357

Jackson: how to put a space after a separator when I serialize a List

Which options should I use to put a space after a comma separator when I serialize a List?

What I have investigated:

  1. I can use @JsonSerialize(contentUsing = MyCustomSerializer.class) on the top of a List field.
  2. Or somehow set up ObjectMapper with .writer(PrettyPrinter pp).

Neither of the options seems suitable.

The result of the serialization I have is {"inq":["2","35"]}. And I want to have: {"inq":["2", "35"]}. With a space after the comma.

Any suggestions are highly appreciated.

Upvotes: 1

Views: 2028

Answers (1)

qfrank
qfrank

Reputation: 272

just extend MinimalPrettyPrinter

    public class TestObjectMapper2 {
        public static void main(String[] args) throws IOException {
            ObjectMapper mapper = new ObjectMapper();
            Person person = mapper.readValue("{\"name\":\"frank\",\"age\":20,\"inq\":[\"2\",\"35\"]}",Person.class);
            System.out.println(mapper.writer(new MinimalPrettyPrinter(){
                @Override
                public void writeObjectEntrySeparator(JsonGenerator jg)
                throws IOException
                {
                    jg.writeRaw(',');
                    jg.writeRaw(' ');
                }

                @Override
                public void writeArrayValueSeparator(JsonGenerator jg)
                throws IOException
                {
                    jg.writeRaw(',');
                    jg.writeRaw(' ');
                }
            }).writeValueAsString(person));
        }

        private static class Person{
            @Override
            public String toString() {
                return "Person{" +
                        "name='" + name + '\'' +
                        ", age=" + age +
                        '}';
            }

            private String name;
            private Integer age;

            private List<String> inq;

            public List<String> getInq()
            {
                return inq;
            }

            public void setInq(List<String> inq)
            {
                this.inq = inq;
            }

            public String getName() {
                return name;
            }

            public void setName(String name) {
                this.name = name;
            }

            public Integer getAge() {
                return age;
            }

            public void setAge(Integer age) {
                this.age = age;
            }
        }
    }

output: {"name":"frank", "age":20, "inq":["2", "35"]}

Upvotes: 1

Related Questions