json字符串忽略null,忽略字段,首字母大写等gson,jackson,fastJson实现demo,T data JSON.parseObject json转换
json字符串忽略null,忽略字段,首字母大写等gson,jackson,fastJson实现demo
package com.example.core.mydemo.json.vo; import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName; import java.util.List; @JsonAutoDetect(fieldVisibility= JsonAutoDetect.Visibility.ANY, getterVisibility=JsonAutoDetect.Visibility.NONE)
public class JsonReqVo { @Expose
@SerializedName("Username") //gson
@JSONField(name= "Username") //fastjson
private String username; @Expose
@JsonProperty("Status")
private String status; //jackson @Expose
private String school;
@Expose
private String password;
@Expose
private String address; @JsonIgnore //可以直接放在field上面表示要忽略的filed //jackson
@Expose(serialize = false) //gson
@JSONField(serialize = false) //fastjson
private String apikey; public String getAddress() {
return address;
} public void setAddress(String address) {
this.address = address;
} public String getSchool() {
return school;
} public void setSchool(String school) {
this.school = school;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
} public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} public String getStatus() {
return status;
} public void setStatus(String status) {
this.status = status;
} public String getApikey() {
return apikey;
} public void setApikey(String apikey) {
this.apikey = apikey;
}
} package com.example.core.mydemo.json; import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper; import java.util.List; public class JsonUtils {
// 定义jackson对象
private static final ObjectMapper MAPPER = new ObjectMapper(); /**
* 将对象转换成json字符串。
* <p>Title: pojoToJson</p>
* <p>Description: </p>
* @param data
* @return
*/
public static String objectToJson(Object data) {
try {
MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL);
//通过该方法对mapper对象进行设置,所有序列化的对象都将按改规则进行系列化 Include.NON_NULL 属性为NULL 不序列化
//Include.Include.ALWAYS 默认
//Include.NON_DEFAULT 属性为默认值不序列化
//Include.NON_EMPTY 属性为 空(“”) 或者为 NULL 都不序列化
//Include.NON_NULL 属性为NULL 不序列化 String string = MAPPER.writeValueAsString(data);
return string;
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
} /**
* 将json结果集转化为对象
*
* @param jsonData json数据
* @param beanType 对象中的object类型
* @return
*/
public static <T> T jsonToPojo(String jsonData, Class<T> beanType) {
try {
MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL);
T t = MAPPER.readValue(jsonData, beanType);
return t;
} catch (Exception e) {
e.printStackTrace();
}
return null;
} /**
* 将json数据转换成pojo对象list
* <p>Title: jsonToList</p>
* <p>Description: </p>
* @param jsonData
* @param beanType
* @return
*/
public static <T> List<T> jsonToList(String jsonData, Class<T> beanType) {
MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL);
JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);
try {
List<T> list = MAPPER.readValue(jsonData, javaType);
return list;
} catch (Exception e) {
e.printStackTrace();
}
return null;
} } package com.example.core.mydemo.json; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.PascalNameFilter;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.example.core.mydemo.json.vo.JsonReqVo;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.junit.Test; import java.util.ArrayList;
import java.util.List; /**
* last print:
* gson={"Username":"刘天王","status":"1","password":"","apikey":"1111111111111"}
* gson2={"Username":"刘天王","status":"1","school":null,"password":"","address":null,"apikey":"1111111111111"}
* gson3={"Username":"刘天王","status":"1","password":""}
* json={"username":"刘天王","password":"","Status":"1"}
* json2={"Username":"刘天王","password":"","status":"1"}
* jsonStr3={"Username":"刘天王","Password":"","Status":"1"}
* jsonStr4={"Username":"刘天王","password":"","status":"1"}
* jsonStr5={"Username":"刘天王","address":null,"password":"","school":null,"status":"1"}
* jsonStr6={"Username":"刘天王","password":"","status":"1"}
* jsonStr7={"Username":"刘天王","password":"","status":"1"}
* jsonStr8={"Username":"刘天王","address":"","password":"","school":"","status":"1"}
* jsonStr9={"Username":"刘天王","password":"","status":"1"}
*
*/
//@RunWith(SpringRunner.class)
//@SpringBootTest()
public class JsonUtilsTest {
@Test
public void test(){
JsonReqVo reqVo = new JsonReqVo();
reqVo.setApikey("1111111111111");
reqVo.setStatus("1");
reqVo.setUsername("刘天王");
reqVo.setPassword("");
reqVo.setSchool(null); //Gson
String g1 = new Gson().toJson(reqVo);
//首字母大写 @SerializedName("Username")
//gson默认忽略null
//gson={"Username":"刘天王","status":"1","password":"","apikey":"1111111111111"}
System.out.println("gson=" + g1); // Both Gson instances must have serializeNulls()
final Gson gson = new GsonBuilder().serializeNulls().create();
//gson2={"Username":"刘天王","status":"1","school":null,"password":"","address":null,"apikey":"1111111111111"}
System.out.println("gson2=" + gson.toJson(reqVo)); GsonBuilder builder = new GsonBuilder();
builder.excludeFieldsWithoutExposeAnnotation();
Gson gson3 = builder.create();
//@Expose(serialize = false) 其他的字段也需要加上
//gson3={"Username":"刘天王","status":"1","password":""}
System.out.println("gson3=" + gson3.toJson(reqVo)); // jackson
String json = JsonUtils.objectToJson(reqVo);
//通过该方法对mapper对象进行设置,所有序列化的对象都将按改规则进行系列化 Include.NON_NULL 属性为NULL 不序列化 //加上 @JsonAutoDetect(fieldVisibility= JsonAutoDetect.Visibility.ANY, getterVisibility=JsonAutoDetect.Visibility.NONE)
/**
* JsonAutoDetect.Visibility.ANY : 表示所有字段都可以被发现, 包括private修饰的字段, 解决大小写问题
* JsonAutoDetect.Visibility.NONE : 表示get方法不可见,解决字段重复问题
*/
//需要将字段设置为首字母大写
//json={"username":"刘天王","password":"","Status":"1"}
System.out.println("json=" + json); // fastJson
//@JSONField(name= "SjAreasNum") 单个字段 默认过滤空值
String ss = JSON.toJSONString(reqVo);
//json2={"Username":"刘天王","apikey":"1111111111111","password":"","status":"1"}
System.out.println("json2=" + ss); //全部的首字母大写 null忽略,空字符串保留
String jsonStr3= JSON.toJSONString(reqVo ,new PascalNameFilter());
//jsonStr3={"Username":"刘天王","Apikey":"1111111111111","Password":"","Status":"1"}
System.out.println("jsonStr3=" + jsonStr3); //QuoteFieldNames:输出key时是否使用双引号,默认为true
String jsonStr4= JSONObject.toJSONString(reqVo, SerializerFeature.QuoteFieldNames);
//jsonStr4={"Username":"刘天王","apikey":"1111111111111","password":"","status":"1"}
System.out.println("jsonStr4=" + jsonStr4); //WriteMapNullValue:是否输出值为null的字段,默认为false
String jsonStr5= JSONObject.toJSONString(reqVo, SerializerFeature.WriteMapNullValue);
//有效
//jsonStr5={"Username":"刘天王","address":null,"apikey":"1111111111111","password":"","school":null,"status":"1"}
System.out.println("jsonStr5=" + jsonStr5); //WriteNullNumberAsZero:数值字段如果为null,输出为0,而非null
String jsonStr6= JSONObject.toJSONString(reqVo, SerializerFeature.WriteNullNumberAsZero);
//jsonStr6={"Username":"刘天王","apikey":"1111111111111","password":"","status":"1"}
System.out.println("jsonStr6=" + jsonStr6); //WriteNullListAsEmpty:List字段如果为null,输出为[],而非null
String jsonStr7= JSONObject.toJSONString(reqVo, SerializerFeature.WriteNullListAsEmpty);
//jsonStr7={"Username":"刘天王","apikey":"1111111111111","password":"","status":"1"}
System.out.println("jsonStr7=" + jsonStr7); //WriteNullStringAsEmpty:字符类型字段如果为null,输出为”“,而非null
String jsonStr8= JSONObject.toJSONString(reqVo, SerializerFeature.WriteNullStringAsEmpty);
//有效
//jsonStr8={"Username":"刘天王","address":"","apikey":"1111111111111","password":"","school":"","status":"1"}
System.out.println("jsonStr8=" + jsonStr8); //WriteNullBooleanAsFalse:Boolean字段如果为null,输出为false,而非null
String jsonStr9= JSONObject.toJSONString(reqVo, SerializerFeature.WriteNullBooleanAsFalse);
//jsonStr9={"Username":"刘天王","apikey":"1111111111111","password":"","status":"1"}
System.out.println("jsonStr9=" + jsonStr9); }
}
json字符串忽略null,忽略字段,首字母大写等gson,jackson,fastJson实现demo,T data JSON.parseObject json转换的更多相关文章
- JS中将字符串中每个单词的首字母大写化
今天看到一个帖子,处理js中字符串每个单词的首字母大写. 原贴地址:关于字符串中每个单词的首字母大写化问题 受到启发,自己跟着改写了几个版本如下,请大家指正. 1.for循环: var a = 'Hi ...
- java字符串根据正则表达式让单词首字母大写
public class Da { public static void main(String[] args) { String s = "hello_*java_*world" ...
- 关于字符串中每个单词的首字母大写化问题之 拆分split(/\s+/)
var a = 'Hi, my name\'s Han Meimei, a SOFTWARE engineer'; //for循环 function titleCase(s) { var i, ss ...
- 使用Jackson解析首字母大写的json字符串
Jackson在解析返回的json字符串时始终报错,纠结很久之后才找到原因,原来是是由于json字符串中的字母都是首字母大写,导致jackson找不到相应的KEY. 在项目中经常使用从服务器获取的数据 ...
- 如果json中的key需要首字母大写怎么解决?
一般我们命名都是驼峰式的,可是有时候和第三方接口打交道,也会遇到一些奇葩,比如首字母大写........额 这是个什么鬼,对方这么要求,那我们也得这么写呀. 于是乎,第一种方式:把类中的字段首字母大写 ...
- javabean转成json字符首字母大写
今天写接口的时候有个需求将接口返回的json字符串首字母大写:{"SN":"","Result":""}格式, 只需要在 ...
- 关于fastjson的一个坑:输出json时,bean对象属性首字母默认被小写
fastjson 是一个性能很好的 Java 语言实现的 JSON 解析器和生成器,来自阿里巴巴. 主要特点: 快速FAST: 比其它任何基于Java的解析器和生成器更快,包括jackson 强大:支 ...
- jackson json序列化 首字母大写 第二个字母需小写
有这样一个类: @Setter @Getter @JsonNaming(value = PropertyNamingStrategy.UpperCamelCaseStrategy.class) pub ...
- JS replace()方法-字符串首字母大写
replace() 方法用于在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的子串. replace()方法有两个参数,第一个参数是正则表达式,正则表达式如果带全局标志/g,则是代表替换 ...
- python字符串的操作(去掉空格strip(),切片,查找,连接join(),分割split(),转换首字母大写, 转换字母大小写...)
#可变变量:list, 字典#不可变变量:元祖,字符串字符串的操作(去掉空格, 切片, 查找, 连接, 分割, 转换首字母大写, 转换字母大小写, 判断是否是数字字母, 成员运算符(in / not ...
随机推荐
- 应对 Job 场景,Serverless 如何帮助企业便捷上云
简介:函数计算作为事件驱动的全托管计算服务,其执行模式天生就与这类 Job 场景非常契合,对上述痛点进行了全方面的支持,助力"任务"的无服务器上云. 作者:冯一博 任务(Jobs) ...
- AI和大数据结合,智能运维平台助力流利说提升核心竞争力
简介: 简介:本文整理自数智创新行--智能运维专场(上海站),流利说最佳实践演讲:<基于SLS千万级在线教育平台统一监控运营实践> 作者:孙文杰 流利说运维总监元乙 阿里云智能技术专家 优 ...
- [FAQ] CodeLlama GGUF 文件下载
hf-mirror: https://hf-mirror.com/TheBloke/CodeLlama-7B-GGUFmodelscope: https://modelscope.cn/models/ ...
- dotnet 已知问题 使用 Directory.EnumerateXXX 方法枚举 C 盘根路径可能错误的问题
在 dotnet 里面,可以使用 Directory.EnumerateXXX 系列方法进行枚举文件或文件夹.在准备枚举驱动器根路径的文件或文件夹时,可能获取到错误的路径.错误的步骤在于传入的是如 C ...
- dotnet 读 WPF 源代码笔记 渲染层是如何将字符 GlyphRun 画出来的
从业务代码构建出来 GlyphRun 对象,在 WPF 的渲染层里,如何利用 GlyphRun 提供的数据将字符在界面呈现出来.本文将和大家聊聊从 WPF 的渲染层获取到 GlyphRun 数据,到调 ...
- dotnet 6 创建进程 Process.Start 时设置 UseShellExecute 在 Windows 下对性能的影响
本文将告诉大家,在 dotnet 6 或 dotnet 7 版本里,启动新的进程时,在 StartInfo 设置 UseShellExecute 为 true 和 false 时,对性能的影响 在 d ...
- 2019-9-2-dotnet-获取当前进程方法
title author date CreateTime categories dotnet 获取当前进程方法 lindexi 2019-9-2 11:3:3 +0800 2019-09-02 10: ...
- Ubuntu VNC 远程桌面及常见问题
一.Ubuntu 远程桌面开启 在ubuntu 设置中打开远程桌面 **注意:如果没有共享桌面选项也不要谎,只需要安装 vino 即可 sudo apt update sudo apt install ...
- Python中强大的通用ORM框架:SQLAlchemy
Python中强大的通用ORM框架:SQLAlchemy https://zhuanlan.zhihu.com/p/444930067
- java程序,如何打印详细报错堆栈信息
try { System.out.println(1/0); } catch (final Exception e) { log.error("ERROR", "Erro ...