春季会得到响应,因为json对铸造



当我去时(浏览器中的URL)到某个URL我得到了与我的课程相匹配的JSON响应(获取响应)。

我想在不使用一些Jackson等Java转换器的情况下将此JSON转换为我的对象。

我可以在这里使用什么春季注释?

我尝试做的是这样的事情,因此它会自动将JSON转换为对象:

@RequestMapping("/getCar") 
public Car getCar(@SOMEANNOTATION(Car car) 
{ return car;}

您可以使用RestTemplate:

进行操作
RestTemplate restTemplate = new RestTemplate();
Car car = restTemplate.getForObject("http://localhost:8080/getCar", Car.class);

您需要一台汽车,因此弹簧可以映射:

@JsonIgnoreProperties(ignoreUnknown = true)
public class Car {
    ...
}

但是您需要了解,春天仍然会使用引擎盖下的某些转换器来创建/读取数据...

您可以尝试此@consumes({" application/json"," application/xml"})

Sring引导文档构建RESTFUL Web服务

还有另一个解决方案

基本上,弹簧转换器会自动处理对象的序列化/次要化。换句话说,在这种情况下,您无事可做。

考虑基本的REST控制器:

package hello;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class GreetingController {
    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();
    @RequestMapping("/greeting")
    public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
        return new Greeting(counter.incrementAndGet(),
                            String.format(template, name));
    }
}

说明

Greeting对象必须转换为JSON。感谢春季的HTTP 消息转换器支持,您无需进行此转换 手动。因为 Jackson 2 在班级路径上,春季 MappingJackson2HttpMessageConverter自动选择转换 Greeting实例到JSON。

您必须使用这样的东西自动将您的请求json转换为java对象。

@RequestMapping("/getCar", method =RequestMethod.POST,
produces=MediaType.APPLICATION_JSON_VALUE,consumes=MediaType.APPLICATION_JSON_VALUE)
public Car getCar(@RequestBody Car car){
    return car;
}

但是,Spring将在后端使用httpmessageconverter将您的JSON请求转换为POJO。这样的东西应该添加到您的@Configuration

public void configureMessageConverters() {
        List<HttpMessageConverter<?> messageConverters = new ArrayList<>();
        messageConverters.add(new MappingJackson2HttpMessageConverter());
        super.configureMessageConverters(converters);
}

相关内容

最新更新