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 ...
随机推荐
- 阿里云消息队列 RocketMQ 5.0 全新升级:消息、事件、流融合处理平台
简介: RocketMQ5.0 的发布标志着阿里云消息从消息领域正式迈向了"消息.事件.流"场景大融合的新局面.未来阿里云消息产品的演进也将继续围绕消息.事件.流核心场景而开展. ...
- 运行模型对比 gemma:7b, llama2, mistral, qwen:7b
[gemma:2b] total duration: 1m5.2381509sload duration: 530.9µsprompt eval duration: 110.304msprompt e ...
- [FE] nvm-windows: Microsoft/NPM/Google 推荐 Windows 的 Node.js 版本管理器, posix 的 nvm-sh/nvm
1. 到 github 下载 nvm-setup.zip 并安装. Releases · coreybutler/nvm-windows (github.com) 2. 安装一个版本的 nodejs. ...
- [Nova] KeyValue Field 设置默认 key 的方式
1. 使用 withMeta: KeyValue::make('options') ->withMeta([ 'value' => $this->options ?? [ 'A' = ...
- [Caddy2] Caddyfile 使用其它 DNS provider
安装 caddy 的 dns provider 模块. https://github.com/caddy-dns/cloudflare 如果是在 Docker 中 build 模块按文档进行,通过 c ...
- petalinux 报错总结
Failed to menu config project component.... 解决办法 此处是由于Terminal(终端)的界面太窄导致的,把Terminal(终端)界面拉宽即可:重新执行命 ...
- VSCode 中安装 esp-idf
一.准备工具 首先需要安装好 VSCode 软件和 esp-idf 环境. 安装 VSCode VSCode 安装比较简单,我就不赘述了,进入官网下载一键安装即可 VSCode官网:https://c ...
- vue引入一个单独的数据文件
1.新建一个address.js的文件 2.文件内const citys = { "北京市": ["东城区","西城区",& ...
- Asynq 实现 Go 异步任务处理
目录 Asynq 实现 Go 异步任务处理 一.概述 二.快速开始 1. 准备工作 2. 安装asynq软件包 3. 创建项目asynq_task 2. Redis连接项 4. Task任务 5. 编 ...
- ansible(2)--ansible的安装与配置文件管理
目录 1 ansible的安装 1.1 yum安装 1.2 pip安装 2 ansible相关文件 2.1 ansible配置文件 2.2 ansible配置文件的优先级 2.3 ansible的主机 ...