У меня есть класс nodejs, который использует fetch
API и вызывает spring web
бэкэнд, используя POST.
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 в качестве весеннего значения по умолчанию вместо Джексона. Когда я отправляю запрос из внешнего интерфейса, он не десериализует запрос, поступающий из внешнего интерфейса для ObjectId.
Из внешнего интерфейса это идет в теле fetch
после JSON .stringify - "{ "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 -
<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 - Весной с Джексоном все работало нормально.