fastjson 转下划线_Java开发里遇到的奇奇怪怪的需求---JSON键值驼峰转下划线的实现...

这篇博客介绍了如何在Java开发中,利用Jackson库的注解`@JsonProperty`和`@JsonAlias`,配合Fastjson,实现驼峰命名到下划线分隔的JSON键值转换。示例代码展示了用户注册场景,通过注解处理,使得接口能够接收和返回驼峰命名或下划线分隔的JSON数据。
摘要由CSDN通过智能技术生成

上周在与第三方对接接口的时候,由于三方的接口key值均是采用下划线命名的方式,使用传统的JSONObject方式,需要挨个赋值,特别麻烦,而且一点也不面向对象,一点也不极客。

大概实现的效果就是上图这样,三方接口提供的无论是入参还是接参,均是下划线分隔的,接口的需求是驼峰的和下划线分隔的均需要能正常接收,并进行业务逻辑处理,好了,话不多说,上代码!

代码见:jjn0942/jackson-demo-project​gitee.comdecd78ec5e5aeef0843cc3ef33f8cedb.png

首先导入Pom依赖,Jackson的三个Jar包和FastJson(可不要,就是习惯了用而已):

com.fasterxml.jackson.core

jackson-core

2.12.0-rc1

com.fasterxml.jackson.core

jackson-annotations

2.12.0-rc1

com.fasterxml.jackson.core

jackson-databind

2.12.0-rc1

com.alibaba

fastjson

1.2.74

我们模拟用户注册的场景,提交一系列基本信息,如:

{

"user_name": "jjn",

"org_id": "01",

"org_name": "Class1",

"age": 0,

"email": "jjn@mail.ustc.edu.cn",

"create_time": "2020-11-01 09:11:03"

}

通过接口处理之后生成的数据如下:

{

"code": 200,

"message": "成功",

"info": {

"update_time": "2020-11-01 22:06:45",

"create_time": "2020-11-01 09:11:03",

"registerTime": "2020-11-01 22:06:45",

"user_name": "jjn",

"org_id": "01",

"registered": true,

"org_name": "Class1",

"age": 0,

"email": "jjn@mail.ustc.edu.cn"

}

}

那么是如何实现的呢?其实主要就是Jackson Json库的几个注解,来看看吧~@JsonProperty

/*** Marker annotation that can be used to define a non-static* method as a "setter" or "getter" for a logical property* (depending on its signature),* or non-static object field to be used (serialized, deserialized) as* a logical property.*

* Default value ("") indicates that the field name is used* as the property name without any modifications, but it* can be specified to non-empty value to specify different* name. Property name refers to name used externally, as* the field name in JSON objects.*

* Starting with Jackson 2.6 this annotation may also be* used to change serialization of Enum like so:*

public enum MyEnum {{@literal @JsonProperty}("theFirstValue") THE_FIRST_VALUE,{@literal @JsonProperty}("another_value") ANOTHER_VALUE;}
* as an alternative to using {@link JsonValue} annotation.*/

注释里面写的很清楚了,指定了value的值之后,在生成JSON的时候,会按value的值来。@JsonAlias

/*** Annotation that can be used to define one or more alternative names for* a property, accepted during deserialization as alternative to the official* name. Alias information is also exposed during POJO introspection, but has* no effect during serialization where primary name is always used.*

* Examples:*

*public class Info {*  @JsonAlias({ "n", "Name" })*  public String name;*}*
** @since 2.9*/

alias的意思是别名,value值指定了之后,可以接受多种可能的赋值。

所以最后我们的用户实体类就会写成这样:

package com.zhihu.jjn.demoproject.entity;

import com.fasterxml.jackson.annotation.JsonAlias;

import com.fasterxml.jackson.annotation.JsonFormat;

import com.fasterxml.jackson.annotation.JsonProperty;

import lombok.AllArgsConstructor;

import lombok.Builder;

import lombok.Data;

import lombok.NoArgsConstructor;

import java.util.Date;

/*** @author Jiang Jining* @date 2020/11/1 10:17*/

@Data

@AllArgsConstructor

@NoArgsConstructor

@Builder

public class User {

@JsonProperty(value = "user_name")

@JsonAlias(value = {"user_name", "userName"})

private String userName;

@JsonProperty(value = "org_id")

@JsonAlias(value = {"org_id", "orgId"})

private String orgId;

@JsonProperty(value = "org_name")

@JsonAlias(value = {"org_name", "orgName"})

private String orgName;

private Integer age;

private String email;

@JsonProperty(value = "create_time")

@JsonAlias(value = {"create_time", "createTime"})

@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")

private Date createTime;

@JsonProperty(value = "update_time")

@JsonAlias(value = {"update_time", "updateTime"})

@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")

private Date updateTime;

private Boolean registered;

@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")

private Date registerTime;

}

返回实体类:

package com.zhihu.jjn.demoproject.entity;

import com.alibaba.fastjson.JSONObject;

import lombok.AllArgsConstructor;

import lombok.Builder;

import lombok.Data;

import lombok.NoArgsConstructor;

/*** @author Jiang Jining* @date 2020/11/1 11:08*/

@Data

@AllArgsConstructor

@Builder

@NoArgsConstructor

public class Response {

private Integer code;

private String message;

private JSONObject info;

public static Response success(JSONObject data) {

return Response.builder().code(200).message("成功").info(data).build();

}

public static Response error(JSONObject data) {

return Response.builder().code(500).message("失败").info(data).build();

}

}

service接口:

package com.zhihu.jjn.demoproject.service;

import com.alibaba.fastjson.JSONObject;

import com.fasterxml.jackson.core.JsonProcessingException;

import com.zhihu.jjn.demoproject.entity.User;

/*** @author Jiang Jining* @date 2020/11/1 11:12*/

public interface UserService {

/*** Register user demo.** @param user user param from front end* @return json object*/

JSONObject registerUser(User user) throws JsonProcessingException;

}

service接口实现:

package com.zhihu.jjn.demoproject.service.impl;

import com.alibaba.fastjson.JSON;

import com.alibaba.fastjson.JSONObject;

import com.fasterxml.jackson.core.JsonProcessingException;

import com.fasterxml.jackson.databind.ObjectMapper;

import com.zhihu.jjn.demoproject.entity.User;

import com.zhihu.jjn.demoproject.service.UserService;

import org.springframework.stereotype.Service;

import java.util.Date;

/*** @author Jiang Jining* @date 2020/11/1 11:12*/

@Service

public class UserServiceImpl implements UserService {

@Override

public JSONObject registerUser(User user) throws JsonProcessingException {

ObjectMapper objectMapper = new ObjectMapper();

user.setRegistered(true);

user.setRegisterTime(new Date());

user.setUpdateTime(new Date());

String string = objectMapper.writeValueAsString(user);

return JSON.parseObject(string);

}

}

最后的Controller实现:

package com.zhihu.jjn.demoproject.controller;

import com.fasterxml.jackson.core.JsonProcessingException;

import com.zhihu.jjn.demoproject.entity.Response;

import com.zhihu.jjn.demoproject.entity.User;

import com.zhihu.jjn.demoproject.service.UserService;

import org.springframework.web.bind.annotation.CrossOrigin;

import org.springframework.web.bind.annotation.PostMapping;

import org.springframework.web.bind.annotation.RequestBody;

import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/*** @author Jiang Jining* @date 2020/11/1 11:06*/

@RestController

@CrossOrigin

public class UserController {

@Resource

private UserService userService;

@PostMapping(value = "/api/user/register")

public Response userRegisterController(@RequestBody User user) throws JsonProcessingException {

return Response.success(userService.registerUser(user));

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值