实体类:
import java.io.Serializable;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor; @Data
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {
/**
*
*/
private static final long serialVersionUID = -329066647199569031L; private String userName; private String orderNo;
}
帮助类:
import java.io.IOException; import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy; /**
* JSON的驼峰和下划线互转帮助类
*
* @author yangzhilong
*
*/
public class JsonUtils { /**
* 将对象的大写转换为下划线加小写,例如:userName-->user_name
*
* @param object
* @return
* @throws JsonProcessingException
*/
public static String toUnderlineJSONString(Object object) throws JsonProcessingException{
ObjectMapper mapper = new ObjectMapper();
mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
mapper.setSerializationInclusion(Include.NON_NULL);
String reqJson = mapper.writeValueAsString(object);
return reqJson;
} /**
* 将下划线转换为驼峰的形式,例如:user_name-->userName
*
* @param json
* @param clazz
* @return
* @throws IOException
*/
public static <T> T toSnakeObject(String json, Class<T> clazz) throws IOException{
ObjectMapper mapper = new ObjectMapper();
// mapper的configure方法可以设置多种配置(例如:多字段 少字段的处理)
//mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
T reqJson = mapper.readValue(json, clazz);
return reqJson;
}
}
单元测试类:
import java.io.IOException; import org.junit.Test; import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException; public class JsonTest { @Test
public void testToUnderlineJSONString(){
User user = new User("张三", "1111111");
try {
String json = JsonUtils.toUnderlineJSONString(user);
System.out.println(json);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
} @Test
public void testToSnakeObject(){
String json = "{\"user_name\":\"张三\",\"order_no\":\"1111111\"}";
try {
User user = JsonUtils.toSnakeObject(json, User.class);
System.out.println(JSONObject.toJSONString(user));
} catch (IOException e) {
e.printStackTrace();
}
}
}
测试结果:
{"user_name":"张三","order_no":"1111111"} {"orderNo":"1111111","userName":"张三"}