我有一个nodejs类,它使用fetch
api并使用POST调用spring web
后端。
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 - 在 Spring 默认使用 Jackson 时工作正常。
最佳答案
HTTP 请求参数 {"someId":"507f1f77bcf86cd799439011"}"表示它是一个字符串字段。 根据您的 ObjectId 类结构,正确的 JSON 类似于 {"someId":{"id":"507f1f77bcf86cd799439011"}},嵌套类 JSON 格式。
关于javascript - Spring boot自定义gson BEGIN_OBJECT但出现STRING错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61515297/