接口请求与对象转json中字段大小写的处理

2 篇文章 0 订阅

1、前端请求对象中,字段为大写的情况

》前端请求对象字段为大写
》后端接受对象字段也为大写
前后端对象字段一模一样,就是接受不到前端传过来的值,针对这种情况,只需在后端对象中加@JsonProperty("Id")即可
如下所示:

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;

@Data
public class AfterResume {
    @JsonProperty("Id")
    private String Id;
    /**
     * 起止时间
     */
    @JsonProperty("YearAndMonth")
    private String YearAndMonth;

    /**
     * 在何单位任职
     */
    @JsonProperty("OrganizationAndJob")
    private String OrganizationAndJob;
}

2、对象转json字符串,但对象中存在字段大写的情况,想要保持对象字段和json字符串格式一直;就不能用fastjson。这里有2中方式可供转换

1)通过com.fasterxml.jackson.databind.ObjectMapper去转换,具体代码如下

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
 
public class Main {
    public static void main(String[] args) throws Exception {
        User user = new User("John", "Doe", 25);
        
        ObjectMapper mapper = new ObjectMapper();
        mapper.setPropertyNamingStrategy(PropertyNamingStrategy.UPPER_CAMEL_CASE); // 设置首字母大写的策略
        
        String json = mapper.writeValueAsString(AfterResume);
        System.out.println(json);
    }
}

2、 第二种通过gson去转换

String json = new Gson().toJson(afterResumes);
System.out.println(json);
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值