java对象驼峰命名属性转JSON下划线命名属性

jackson实现:

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;

public static void main(String[] args) throws JsonProcessingException {
        User user = new User();
        user.setUserName("李华");
        user.setUserAge("18");
        ObjectMapper mapper = new ObjectMapper();
        mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
        String json = mapper.writeValueAsString(user);
    }

fastjson实现:
在实体类属性上加@JSONField注解

import com.alibaba.fastjson.annotation.JSONField;
@Data
class  User{
    @JSONField(name = "user_name")
    private String userName;

    @JSONField(name = "user_age")
    private String userAge;
}

   public static void main(String[] args){
        User user = new User();
        user.setUserName("李华");
        user.setUserAge("18");
        String json = JSON.toJSONString(user);
    }


版权声明:本文为weixin_44117767原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。