gpt4 book ai didi

Java spring Rest服务不强制转换参数

转载 作者:太空宇宙 更新时间:2023-11-04 11:41:16 25 4
gpt4 key购买 nike

我正在使用 springFramework 创建 REST api。从post api创建产品,但rest方法不会使用TitleCase参数名称转换参数。

我的产品型号:

public class Product extends BaseModel {

private String title;
private String shortDescription;

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

public String getShortDescription() {
return shortDescription;
}

public void setShortDescription(String shortDescription) {
this.shortDescription = shortDescription;
}
}

我的产品 REST Api:

@PostMapping(value = "/product", consumes = {MediaType.APPLICATION_JSON_VALUE})
public ApiResponse Insert(@RequestBody Product model){
ApiResponse response = new ApiResponse();

try{
response.setData(_service.Insert(model));
response.setSuccess(true);
} catch (Exception ex){
response = _service.HandleException(ex);
}

return response;
}

已处理的请求对象:

{
"title" : "TEST",
"shortDescription" : "SD",
"longDescription" : "LD"
}

未工作的请求对象:

{
"Title" : "TEST",
"ShortDescription" : "SD",
"LongDescription" : "LD"
}

我希望这两个选项都能工作。我是Java新手,所以我不知道如何解决它,所以我想问一下。

已更新

jackson 配置文件

@Configuration
@EnableWebMvc
public class JacksonConfiguration {
@Bean
public ObjectMapper objectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);

return mapper;
}
}

谢谢。

最佳答案

这工作正常:

package com.example;

import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;
import org.junit.Test;


import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;

public class Test {

private ObjectMapper mapper;

public static class A{

private int test;

public int getTest() {
return test;
}

public void setTest(int test) {
this.test = test;
}
}

@Before
public void setUp(){
mapper = new ObjectMapper();
mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
}

@Test
public void deserialise() throws Exception {
String json = "{\"test\":\"2\"}";
assertThat(mapper.readValue(json, A.class).getTest(), is(2));
}

@Test
public void deserialiseIgnoringCase() throws Exception {
String json = "{\"Test\":\"2\"}";
assertThat(mapper.readValue(json, A.class).getTest(), is(2));
}

}

关于Java spring Rest服务不强制转换参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42750188/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com