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转换的更多相关文章

  1. JS中将字符串中每个单词的首字母大写化

    今天看到一个帖子,处理js中字符串每个单词的首字母大写. 原贴地址:关于字符串中每个单词的首字母大写化问题 受到启发,自己跟着改写了几个版本如下,请大家指正. 1.for循环: var a = 'Hi ...

  2. java字符串根据正则表达式让单词首字母大写

    public class Da { public static void main(String[] args) { String s = "hello_*java_*world" ...

  3. 关于字符串中每个单词的首字母大写化问题之 拆分split(/\s+/)

    var a = 'Hi, my name\'s Han Meimei, a SOFTWARE engineer'; //for循环 function titleCase(s) { var i, ss  ...

  4. 使用Jackson解析首字母大写的json字符串

    Jackson在解析返回的json字符串时始终报错,纠结很久之后才找到原因,原来是是由于json字符串中的字母都是首字母大写,导致jackson找不到相应的KEY. 在项目中经常使用从服务器获取的数据 ...

  5. 如果json中的key需要首字母大写怎么解决?

    一般我们命名都是驼峰式的,可是有时候和第三方接口打交道,也会遇到一些奇葩,比如首字母大写........额 这是个什么鬼,对方这么要求,那我们也得这么写呀. 于是乎,第一种方式:把类中的字段首字母大写 ...

  6. javabean转成json字符首字母大写

    今天写接口的时候有个需求将接口返回的json字符串首字母大写:{"SN":"","Result":""}格式, 只需要在 ...

  7. 关于fastjson的一个坑:输出json时,bean对象属性首字母默认被小写

    fastjson 是一个性能很好的 Java 语言实现的 JSON 解析器和生成器,来自阿里巴巴. 主要特点: 快速FAST: 比其它任何基于Java的解析器和生成器更快,包括jackson 强大:支 ...

  8. jackson json序列化 首字母大写 第二个字母需小写

    有这样一个类: @Setter @Getter @JsonNaming(value = PropertyNamingStrategy.UpperCamelCaseStrategy.class) pub ...

  9. JS replace()方法-字符串首字母大写

    replace() 方法用于在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的子串. replace()方法有两个参数,第一个参数是正则表达式,正则表达式如果带全局标志/g,则是代表替换 ...

  10. python字符串的操作(去掉空格strip(),切片,查找,连接join(),分割split(),转换首字母大写, 转换字母大小写...)

    #可变变量:list, 字典#不可变变量:元祖,字符串字符串的操作(去掉空格, 切片, 查找, 连接, 分割, 转换首字母大写, 转换字母大小写, 判断是否是数字字母, 成员运算符(in / not ...

随机推荐

  1. 代码安全无忧—云效Codeup代码加密技术发展之路

    简介: 从代码服务及代码安全角度出发,看看云效代码加密技术如何解决这一问题 代码数据存在云端,如何保障它的安全? 部分企业管理者对于云端代码托管存在一丝担心:我的代码存在云端服务器,会不会被泄露? 接 ...

  2. Vineyard 加入 CNCF Sandbox,将继续瞄准云原生大数据分析领域

    简介: Vineyard 是一个专为云原生环境下大数据分析场景中端到端工作流提供内存数据共享的分布式引擎,我们很高兴宣布 Vineyard 在 2021 年 4 月 27 日被云原生基金会(CNCF) ...

  3. Kubernetes 已经成为云原生时代的安卓,这就够了吗?

    ​简介:本文将介绍如何在 Kubernetes 上构建新的应用管理平台,提供一层抽象以封装底层逻辑,只呈现用户关心的接口,使用户可以只关注自己的业务逻辑,管理应用更快更安全. 作者:司徒放 导语:云原 ...

  4. [Go] flag package 指南: 命令行参数标记的解析

    flag 是 Golang 的官方包. 支持用法有三种,不同之处是二三两种用法是 Var() 函数可以绑定 flag 到一个变量上. 直接调用指定类型的函数有多种,如 flag.String(), B ...

  5. dotnet 修复 GitHub Action 构建过程提示 NETSDK1127 错误

    本文告诉大家,如何修复 GitHub Action 构建过程提示 error NETSDK1127: The targeting pack Microsoft.WindowsDesktop.App.W ...

  6. WPF 已知问题 Popup 吃掉 PreviewMouseDown 事件

    在 WPF 中,使用 Popup 也许会看到 PreviewMouseDown 事件被吃掉 因为 PreviewMouseDown 是 RoutingStrategy.Direct 路由事件,不能在多 ...

  7. 《MySql必知必会》笔记整理

    数据库基础 关键词: 数据库 表(表名唯一,取决多个因素,如不同数据库的表可以同名) 模式(关于数据库和表的布局及特性的信息) 列(表中的字段) 行[行(raw)和记录(record)很大程度可以等同 ...

  8. 火山引擎VeDI:如何高效使用A/B实验,优化APP推荐系统

    更多技术交流.求职机会,欢迎关注字节跳动数据平台微信公众号,回复[1]进入官方交流群 在移动互联网飞速发展的时代,用户规模和网络信息量呈现出爆炸式增长,信息过载加大了用户选择的难度,这样的背景下,推荐 ...

  9. vue使用promise.all异步实现多个请求完成之后在执行某些操作

    使用场景:多个请求方法拿到数据之后需要对这不同的数据进行比较,之后在输出并渲染 思路:使用promise.all()异步操作: Promise.all([ //上架 new Promise((reso ...

  10. telegraph + influxdb + grafana 实现交换机流量展示

    实验环境 influxdb2:2.7.5 telegraf:1.30.1 grafana:10.4.2 influxdb 官方文档见https://docs.influxdata.com/influx ...