|
| 1 | +package io.avaje.jsonb.jackson; |
| 2 | + |
| 3 | +import com.fasterxml.jackson.core.JsonFactory; |
| 4 | +import com.fasterxml.jackson.core.JsonParser; |
| 5 | +import com.fasterxml.jackson.core.SerializableString; |
| 6 | +import com.fasterxml.jackson.core.io.CharacterEscapes; |
| 7 | +import io.avaje.jsonb.Jsonb; |
| 8 | +import org.example.Address; |
| 9 | +import org.example.MyComponent; |
| 10 | +import org.junit.jupiter.api.Test; |
| 11 | + |
| 12 | +import static org.assertj.core.api.Assertions.assertThat; |
| 13 | + |
| 14 | +class JacksonAdapterTest { |
| 15 | + |
| 16 | + public static final JsonFactory JSON_FACTORY = new JsonFactory() |
| 17 | + .configure(JsonParser.Feature.ALLOW_COMMENTS, true) |
| 18 | + .configure(JsonParser.Feature.ALLOW_YAML_COMMENTS, true) |
| 19 | + .configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true) // required to read line breaks |
| 20 | + .configure(JsonParser.Feature.ALLOW_TRAILING_COMMA, true); |
| 21 | + |
| 22 | + public static final JsonFactory HUMAN_READABLE_JSON_FACTORY = JSON_FACTORY.copy() |
| 23 | + .setCharacterEscapes(new HumanReadableCharacterEscapes()); |
| 24 | + |
| 25 | + @Test |
| 26 | + void custom_JsonFactory() { |
| 27 | + |
| 28 | + JacksonAdapter jacksonAdapter = new JacksonAdapter(false, false, false, HUMAN_READABLE_JSON_FACTORY); |
| 29 | + |
| 30 | + Jsonb jsonb = Jsonb.newBuilder() |
| 31 | + .adapter(jacksonAdapter) |
| 32 | + .add(new MyComponent()) |
| 33 | + .build(); |
| 34 | + |
| 35 | + String jc = "\n// a comment \n ## yaml-comment \n{\"street\":\"my-street\nwith-new-lines\tand-tabs\"}"; |
| 36 | + |
| 37 | + Address address = jsonb.type(Address.class).fromJson(jc); |
| 38 | + assertThat(address.street()).isEqualTo("my-street\n" + |
| 39 | + "with-new-lines\tand-tabs"); |
| 40 | + |
| 41 | + Address withHumanNewLinesEtc = new Address(); |
| 42 | + withHumanNewLinesEtc.street("my-street\nwith-new-lines\tand-tabs"); |
| 43 | + |
| 44 | + String asJson = jsonb.toJson(withHumanNewLinesEtc); |
| 45 | + assertThat(asJson).isEqualTo("{\"street\":\"my-street\n" + |
| 46 | + "with-new-lines\tand-tabs\"}"); |
| 47 | + } |
| 48 | + |
| 49 | + private static class HumanReadableCharacterEscapes extends CharacterEscapes { |
| 50 | + private static final long serialVersionUID = 1L; |
| 51 | + |
| 52 | + private static final int[] asciiEscapes = CharacterEscapes.standardAsciiEscapesForJSON(); |
| 53 | + static { |
| 54 | + asciiEscapes['\t'] = CharacterEscapes.ESCAPE_NONE; |
| 55 | + asciiEscapes['\r'] = CharacterEscapes.ESCAPE_NONE; |
| 56 | + asciiEscapes['\n'] = CharacterEscapes.ESCAPE_NONE; |
| 57 | + } |
| 58 | + |
| 59 | + @Override |
| 60 | + public SerializableString getEscapeSequence(final int ch) { |
| 61 | + return null; |
| 62 | + } |
| 63 | + |
| 64 | + @Override |
| 65 | + public int[] getEscapeCodesForAscii() { |
| 66 | + return asciiEscapes; |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | +} |
0 commit comments