Javascript Spring启动自定义gson BEGIN_对象,但为字符串错误

Javascript Spring启动自定义gson BEGIN_对象,但为字符串错误,javascript,java,node.js,spring,spring-boot,Javascript,Java,Node.js,Spring,Spring Boot,我有一个nodejs类,它使用fetchapi并使用POST调用springweb后端 fetch(this.service, { method: 'POST', // *GET, POST, PUT, DELETE, etc. mode: 'cors', // no-cors, *cors, same-origin cache: 'no-cache', // *default, no-cache, reload, forc

我有一个nodejs类,它使用
fetch
api并使用POST调用
springweb
后端

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作为春季的默认设置,而不是Jackson。当我从前端发送一个请求时,它并没有针对ObjectId反序列化来自前端的请求

从前端开始,在JSON.stringify-“{”someId:“507f1f77bcf86cd799439011”之后的
fetch的主体中

在后端,这是一个错误-

 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>

org.springframework.boot
SpringBootStarterWeb
org.springframework.boot
spring启动程序json
我还添加了这个类,但它仍然不适用于objectid-

@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;
    }
}
@配置
公共类GsonConfig实现WebMVCConfiguer{
@凌驾
public void configureMessageConverters(列表来自您的错误消息:

应为BEGIN\u对象,但在第1行第12列路径$.someId处为字符串

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

Convert错误可能是因为您传递了`someId'的字符串,但在类中,它是一个对象(ObjectId),您可以更改ObjectId->string,然后重试。

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

谢谢,我想在后端将其保留为ObjectId。是否可以从前端传递符合要求的数据?从前端传递ObjectId时应该传递什么?或者是否有方法告诉gson使用自定义映射器或其他方法将十六进制字符串序列化为ObjectId?当然,您需要传递正确的JSON参数来自FE.
{“someId”:“507f1f77bcf86cd799439011”
表示它是一个字符串字段。根据您的ObjectId类结构,正确的JSON类似于
{“someId”:{“id”:“507f77bcf86cd799439011”}
谢谢,它工作了。我使用了var ObjectId=require('mongodb')。ObjectId;var ObjectId=new ObjectId()你能把它作为答案贴出来吗,这样我就可以接受了。当然,我会贴出来的