【问题标题】:Spring boot custom gson BEGIN_OBJECT but was STRING errorSpring boot自定义gson BEGIN_OBJECT但出现STRING错误
【发布时间】:2020-04-30 03:12:26
【问题描述】:

我有一个使用 fetch api 并使用 POST 调用 spring web 后端的 nodejs 类。

fetch(this.service, {
            method: 'POST', // *GET, POST, PUT, DELETE, etc.
            mode: 'cors', // no-cors, *cors, same-origin
            cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
            credentials: 'same-origin', // include, *same-origin, omit
            headers: {
                'Content-Type': 'application/json'
                // 'Content-Type': 'application/x-www-form-urlencoded',
            },
            redirect: 'follow', // manual, *follow, error
            referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
            body: JSON.stringify(this.request) // body data type must match "Content-Type" header
        }).then(res => res.json())
        .then((result) => {
            if(result.responseStatus === 'OK'){
                resolve(result);
            }else{
                console.log("failed response");
                console.log(result);
            }
        }, (error) => {
            //handle error here
            console.log("errored response");
            console.log(error);
        });

在后端我有这个 -

@Controller
@CrossOrigin(origins = "http://localhost:3000")
@RequestMapping(value = "/user", method = { RequestMethod.GET,
        RequestMethod.POST }, produces = MediaType.APPLICATION_JSON_VALUE, headers = "Accept="
                + MediaType.APPLICATION_JSON_VALUE)
public class SomeController {

    private final SomeDALImpl repository;
    private SomeResponse response;

    @Autowired
    public SomeController(SomeDALImpl repo) {
        this.repository = repo;
    }

    @RequestMapping("/abcd")
    @ResponseBody
    public SomeResponse getSome(@RequestBody @Valid SomeGetRequest request) {
        response = new SomeResponse();
        //does something
        return response;
    }
}

SomeGetRequest 是一个看起来像这样的类 -

public class SomeGetRequest{
    public ObjectId someId;
    //other getter setters
}

我正在尝试使用 gson 作为我在 spring 中的默认值,而不是 Jackson。当我从前端发送请求时,它不会反序列化来自前端的 ObjectId 请求。

在 JSON.stringify 之后从前端进入 fetch 的正文 - "{"someId":"507f1f77bcf86cd799439011"}"

在后端,这是错误 -

 org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver 
[http-nio-8080-exec-6] Resolved [org.springframework.http.converter.HttpMessageNotReadableException: 
Could not read JSON: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was 
STRING at line 1 column 12 path $.userId; nested exception 
is com.google.gson.JsonSyntaxException: 
java.lang.IllegalStateException: Expected BEGIN_OBJECT but 
was STRING at line 1 column 12 path $.someId]

我在 application.properties 中有这个 - spring.http.converters.preferred-json-mapper = gson 我在 pom.xml 中删除了 Jackson 依赖项 -

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <!-- Exclude the default Jackson dependency -->
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-json</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

我也添加了这个类,但它仍然不适用于 ObjectIds -

@Configuration
public class GsonConfig implements WebMvcConfigurer {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(customGsonHttpMessageConverter());

        extendMessageConverters(converters);
    }

    private GsonHttpMessageConverter customGsonHttpMessageConverter() {
        GsonBuilder builder = new GsonBuilder().registerTypeAdapter(ObjectId.class, new JsonSerializer<ObjectId>() {
            @Override
            public JsonElement serialize(ObjectId src, Type typeOfSrc, JsonSerializationContext context) {
                return new JsonPrimitive(src.toHexString());
            }
        }).registerTypeAdapter(ObjectId.class, new JsonDeserializer<ObjectId>() {
            @Override
            public ObjectId deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                    throws JsonParseException {
                return new ObjectId(json.getAsString());
            }
        });
        Gson gson = builder.create();
        GsonHttpMessageConverter gsonMessageConverter = new GsonHttpMessageConverter();
        gsonMessageConverter.setGson(gson);

        return gsonMessageConverter;
    }
}

或者,也许我没有从前端正确发送请求正文。我该怎么做才能纠正这个问题。谢谢,我是 Spring 新手。

PS - 在春季,Jackson 作为默认设置运行良好。

【问题讨论】:

    标签: javascript java node.js spring spring-boot


    【解决方案1】:

    HTTP 请求参数 {"someId":"507f1f77bcf86cd799439011"}" 表示它是一个字符串字段。 取决于您的 ObjectId 类结构,正确的 JSON 类似于 {"someId":{"id":"507f1f77bcf86cd799439011"}},嵌套类 JSON 格式。

    【讨论】:

      【解决方案2】:

      来自您的错误消息:

      应为 BEGIN_OBJECT,但在第 1 行第 12 列路径 $.someId 处为 STRING

      而且您的对象 SomeGetRequest 没有字符串类型 someId。

      转换错误可能是因为您为`someId传递了一个字符串,但在类中,它是一个对象(ObjectId),您可以更改ObjectId -> String,然后再试一次。

      【讨论】:

      • 谢谢,我想将它作为 ObjectId 保留在后端。是否可以从前端传递合规数据?我应该从前端为 ObjectId 传递什么?或者有没有办法告诉 gson 使用一些自定义映射器或其他东西将十六进制字符串序列化为 ObjectId?
      • 关闭原因,您需要从 FE 传递正确的 JSON 参数。 {"someId":"507f1f77bcf86cd799439011"}" 表示它是一个字符串字段。取决于您的 ObjectId 类结构,正确的 JSON 类似于 {"someId":{"id":"507f1f77bcf86cd799439011"}}
      • 谢谢,它成功了。我用 var ObjectID = require('mongodb').ObjectID; var objectId = new ObjectID();它奏效了。
      • 您能否将其发布为答案,以便我接受。
      • 好的,我会发的
      猜你喜欢
      • 2022-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-27
      • 1970-01-01
      • 2013-04-05
      • 2019-10-01
      • 1970-01-01
      相关资源
      最近更新 更多