Spring Boot reads Json String as an object

Spring Boot Jackson

Spring boot uses jackson to serialize the object and deserialize a string as an object.

an example of serialization

The following code will automatically convert the ResourceDefinition object into a json

    @RequestMapping(value = "/select", method = RequestMethod.GET)
    public ResourceDefinition select(@RequestParam("rid") String rid) {
        log.info(String.format("[*] select resource Rid: %s", rid));
        ResourceDefinition resourceDefinition = resourceService.getResourceDefinition(rid);
        // if the target resource definition is not found, then null content will
        // be returned
        log.info(String.format("[*] select resource definition: %s", resourceDefinition));
        return (resourceDefinition);
    }

an example of deserialization

The following code use objectMapper ( objectMapper = new ObjectMapper()) which is from jackson to deserialize the json into an ojbect.

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public MsgResponseSimple update(@RequestParam("rid") String rid, @RequestParam("definition") String definition) throws Exception {
        MsgResponseSimple msgResponseSimple;
        ResourceDefinition resourceDefinition = objectMapper.readValue(definition, ResourceDefinition.class);
        System.out.println("/update " + resourceDefinition);
        try {
            resourceService.setResourceDefinitionRepository(rid, resourceDefinition);
            msgResponseSimple = new MsgResponseSimple(200, "OK");
        } catch (Exception e) {
            msgResponseSimple = new MsgResponseSimple(201, "Fail");
        }
        return msgResponseSimple;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值