gson 从Json Boot 时出现错误,语法异常:java.lang.IllegalStateException:应为开始_OBJECT,但在第行为STRING

qv7cva1a  于 2022-11-06  发布在  Java
关注(0)|答案(1)|浏览(221)

通过调用api,我得到了如下所示JSON:

{"birthDate":"2002-06-09T22:57:10.0756471Z","created":"2022-06-09T22:57:10.0756471Z","idNumber":"1234567","lastName":"Tester"}

我已经确认JSON是正确的,我在网上验证了它,它也验证了。
我的应用程序得到了这个响应,并正确地处理了它,没有任何问题。 Postman 也是如此。
但是,当将此Json响应字符串转换为我的类时,Springboot中的MockMvc测试失败,并出现错误:

*******java.lang.IllegalStateException:预期为开始_OBJECT,但在第1行第15列路径$.birthDate处为STRING

我做转换喜欢:

MockHttpServletResponse response = mvc.perform(
        post("/examples")
                .accept(MediaType.APPLICATION_JSON)
                .contentType(MediaType.APPLICATION_JSON)
                .content(String.valueOf(postData)))
        .andExpect(status().isOk())
        .andExpect(content().contentType(MediaType.APPLICATION_JSON))
        .andReturn()
        .getResponse();

String responseString = response.getContentAsString(); // returns string like "{"birthDate":"2002-06-09....}"
Gson gson = new Gson();
ExampleResponse exampleResponse = gson.fromJson(responseString, ExampleResponse.class);  // this line fails

我的ExampleResponse类是:

public class ExampleResponse {

    private String idNumber;
    private String lastName;
    private OffsetDateTime birthDate;       
    private OffsetDateTime created;

    /// getters and setters   
}

我不明白为什么fromJson调用失败。

ogq8wdun

ogq8wdun1#

需要在GsonBuilder中注册OffsetDateTime,如下所示:
添加一个类,如:

public class OffsetDateTimeDeserializer implements JsonDeserializer<OffsetDateTime> {

    @Override
    public OffsetDateTime deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
        return OffsetDateTime.parse(jsonElement.getAsString(), DateTimeFormatter.ISO_OFFSET_DATE_TIME);
    }
}

,然后将上面使用Gson将Json字符串转换为模型类的代码修改为:

MockHttpServletResponse response = mvc.perform(
        post("/examples")
                .accept(MediaType.APPLICATION_JSON)
                .contentType(MediaType.APPLICATION_JSON)
                .content(String.valueOf(postData)))
        .andExpect(status().isOk())
        .andExpect(content().contentType(MediaType.APPLICATION_JSON))
        .andReturn()
        .getResponse();

String responseString = response.getContentAsString(); 

        String responseString = response.getContentAsString();
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.registerTypeAdapter(OffsetDateTime.class, new OffsetDateTimeDeserializer());

        Gson gson = gsonBuilder.setPrettyPrinting().create();

ExampleResponse exampleResponse = gson.fromJson(responseString, ExampleResponse.class);  // NOW IT WORKS!!!

相关问题