Is there a bug in the new Spring JSON reader or am I doing something wrong?

ⅰ亾dé卋堺 提交于 2021-02-08 08:13:33

问题


I've got the following reader configured:

@Configuration
public class ReaderConfig {
    @Bean
    public JsonItemReader<String> jsonItemReader(Resource resource) {
        return new JsonItemReaderBuilder<String>()
                .jsonObjectReader(new JacksonJsonObjectReader<>(String.class))
                .resource(resource)
                .name("jsonItemReader")
                .build();
    }
}

With this test:

@Test
public void jsonItemReaderTest() throws Exception {
    ReaderConfig config = new ReaderConfig();

    Resource sampleJsonResource = new ClassPathResource("sampleResponse.json");

    JsonItemReader<String> reader = config.jsonItemReader(sampleJsonResource);

    reader.open(new ExecutionContext());

    String item = null;
    List<String> results = new ArrayList<>();
    do {
        item = reader.read();
        System.err.println(item);
        if (!Objects.isNull(item)) {
            results.add(item);
        }
    } while (item != null);

    reader.close();

    assertThat(results).hasSize(7);
}

and the following JSON:

[
  "A",
  "B",
  "C",
  "D",
  "E",
  "F",
  "G"
]

However, the reader returns null. Trying to trace with the debugger, what I'm getting is that the parser returns back that it has a string at the beginning of the array and there's an expectation that there should instead be an opening brace. Any pointers on this? It seems like such an obvious use case that I'm surprised it isn't covered by the code.


回答1:


The JsonItemReader is designed to read an array of JSON objects (See its Javadoc). According to http://www.json.org, a JSON object is defined as follows:

An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).

So according to this definition, your JSON input is not an array of JSON objects.

Hope this helps.



来源:https://stackoverflow.com/questions/53124746/is-there-a-bug-in-the-new-spring-json-reader-or-am-i-doing-something-wrong

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!