在spring boot项目中已经包含有json序列化的框架,具体在包com.fasterxml.jackson.annotation中,建议看看详细源码。

但在项目应用上还是会有一些坑会出现的,举个例子:

在一个复杂的业务模型中包含有200个字段,在查询列表时只查询其中某20个字段,在查询详情中需要把所有字段都查询出来

一般情况下,如果是开始做一个新功能,那么我们的设计应该类似是这样的:

model

---- QueryModel ,包含20个字段,响应查询列表结果

---- DetailModel extend POJO , 包含所有字段,响应查询实体结果

entity

---- POJO,包含所有字段

但维护从来都是一件蛋疼的事情,200个字段是迭代出来的,他们的逻辑是这样的:

entity

---- POJO,包含所有字段,响应查询列表和查询实体结果

这时候会发现一切蛋疼的原因就是直接把pojo拿来当model用了导致所有参数和结果无法拓展。为什么会这么蛋疼呢?原因不重要,如何解决才重要。

方案1:代码解耦,改造成model和entity分离

此方案的好处是一劳永逸,后续的拓展也比较轻松,弊端也显而易见,会发费许多时间去理解业务重构业务,而且一个稳定的系统一般不会尝试大范围的改造,万一改后出现一堆bug呢?

方案2:把不输出到页面的字段忽略掉

这时候用到注解 @JsonIgnore,该注解既可以作用在字段上也可以作用在方法上(另外两种先不说),可以看看源码和注释:

package com.fasterxml.jackson.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; /**
* Marker annotation that indicates that the logical property that
* the accessor (field, getter/setter method or Creator parameter
* [of {@link JsonCreator}-annotated constructor or factory method])
* is to be ignored by introspection-based
* serialization and deserialization functionality.
*<p>
* Annotation only needs to be added to one of the accessors (often
* getter method, but may be setter, field or creator parameter),
* if the complete removal of the property is desired.
* However: if only particular accessor is to be ignored (for example,
* when ignoring one of potentially conflicting setter methods),
* this can be done by annotating other not-to-be-ignored accessors
* with {@link JsonProperty} (or its equivalents). This is considered
* so-called "split property" case and allows definitions of
* "read-only" (read from input into POJO) and "write-only" (write
* in output but ignore on output)
*<br>
* NOTE! As Jackson 2.6, there is a new and improved way to define
* `read-only` and `write-only` properties, using
* {@link JsonProperty#access()} annotation: this is recommended over
* use of separate <code>JsonIgnore</code> and {@link JsonProperty}
* annotations.
*<p>
* For example, a "getter" method that would otherwise denote
* a property (like, say, "getValue" to suggest property "value")
* to serialize, would be ignored and no such property would
* be output unless another annotation defines alternative method to use.
*<p>
* When ignoring the whole property, the default behavior if encountering
* such property in input is to ignore it without exception; but if there
* is a {@link JsonAnySetter} it will be called instead. Either way,
* no exception will be thrown.
*<p>
* Annotation is usually used just a like a marker annotation, that
* is, without explicitly defining 'value' argument (which defaults
* to <code>true</code>): but argument can be explicitly defined.
* This can be done to override an existing `JsonIgnore` by explicitly
* defining one with 'false' argument: either in a sub-class, or by
* using "mix-in annotations".
*/
@Target({ElementType.ANNOTATION_TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotation
public @interface JsonIgnore
{
/**
* Optional argument that defines whether this annotation is active
* or not. The only use for value 'false' if for overriding purposes
* (which is not needed often); most likely it is needed for use
* with "mix-in annotations" (aka "annotation overrides").
* For most cases, however, default value of "true" is just fine
* and should be omitted.
*/
boolean value() default true;
}

因此在使用的时候需要注意,如果只需要在查询的时候忽略,在保存的时候不忽略,那么需要在getter方法上注解@JsonIgnore,在setter方法上注解 @JsonProperty,(这时候如果使用的lombok就很尴尬了),举个例子:

public class TestEntity{private String name;

    /**
* getter
*/
@JsonIgnore
public String getName() {
return name;
} /**
* setter
*/
@JsonProperty
public void setName(String name) {
this.name= name;
}
}

然后在sql上从select *改成select 指定字段,解决查询列表问题。

然而,在查询单个实体详情的时候这些被忽略的字段也无法传到前端了,这是一条乍一看很理想的死胡同。

但从sql的角度上可以看出select 指定字段的时候,在反序列化到pojo的时候其他字段是没有值的,那么可以把方案换一下,让有值得字段序列化出去,没有值的不序列化

方案3:让有值得字段序列化出去,没有值的不序列化

sql上从select *改成select 指定字段

在pojo里用上@JsonInclude(JsonInclude.Include.NON_NULL)

此时既满足查询列表,又满足查询详情,解决问题。

(七)json序列化的更多相关文章

  1. python网络编程-Json序列化功能扩展-软件开发架构-OSI七层协议-TCP-01

    面向对象补充知识点(面向对象的应用) 扩展json序列化所支持的数据类型(分析源码) import json from datetime import datetime, date # ------- ...

  2. Newtonsoft.Json C# Json序列化和反序列化工具的使用、类型方法大全 C# 算法题系列(二) 各位相加、整数反转、回文数、罗马数字转整数 C# 算法题系列(一) 两数之和、无重复字符的最长子串 DateTime Tips c#发送邮件,可发送多个附件 MVC图片上传详解

    Newtonsoft.Json C# Json序列化和反序列化工具的使用.类型方法大全   Newtonsoft.Json Newtonsoft.Json 是.Net平台操作Json的工具,他的介绍就 ...

  3. Newtonsoft.Json 序列化和反序列化 以及时间格式 2 高级使用

    手机端应用讲究速度快,体验好.刚好手头上的一个项目服务端接口有性能问题,需要进行优化.在接口多次修改中,实体添加了很多字段用于中间计算或者存储,然后最终用Newtonsoft.Json进行序列化返回数 ...

  4. .Net深入实战系列—JSON序列化那点事儿

    序 当前主流的序列化JSON字符串主要有两种方式:JavaScriptSerializer及Json.net(Nuget标识:Newtonsoft.Json).JavaScriptSerializer ...

  5. Newtonsoft.Json 序列化和反序列化 时间格式【转】

    1.JSON序列化 string JsonStr= JsonConvert.SerializeObject(Entity); eg:   A a=new A(); a.Name="Elain ...

  6. [.net 面向对象程序设计进阶] (13) 序列化(Serialization)(五) Json 序列化利器 Newtonsoft.Json 及 通用Json类

    [.net 面向对象程序设计进阶] (13) 序列化(Serialization)(五) Json 序列化利器 Newtonsoft.Json 及 通用Json类 本节导读: 关于JSON序列化,不能 ...

  7. DotNet的JSON序列化与反序列化

    JSON(JavaScript Object Notation)JavaScript对象表示法,它是一种基于文本,独立于语言的轻量级数据交换格式.在现在的通信中,较多的采用JSON数据格式,JSON有 ...

  8. C#中JSON序列化和反序列化

    有一段时间没有到博客园写技术博客了,不过每天逛逛博客园中大牛的博客还是有的,学无止境…… 最近在写些调用他人接口的程序,用到了大量的JSON.XML序列化和反序列化,今天就来总结下json的序列化和反 ...

  9. 使用JSON.Net(Newtonsoft.Json)作为ASP.Net MVC的json序列化和反序列化工具

    ASP.Net MVC默认的JSON序列化使用的是微软自己的JavaScriptSerializer.性能低不说,最让人受不了的是Dictionary<,>和Hashtable类型居然对应 ...

随机推荐

  1. 获取当前时间CTime

    std::string getcurtime(){ USES_CONVERSION; CTime z_CurTime; CString z_TimeStr; z_CurTime = CTime::Ge ...

  2. Glide实现查看图片和保存图片到手机

    两种方式, 推荐方式一 方式一 downloadOnly 创建一个 ImageActivity public class ImageActivity extends AppCompatActivity ...

  3. 旋转数组的最小数字(C++ 和 Python 实现)

    (说明:本博客中的题目.题目详细说明及参考代码均摘自 “何海涛<剑指Offer:名企面试官精讲典型编程题>2012年”) 题目 把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的 ...

  4. maven学习(六)依赖、聚合、继承

    先说一下概念(个人理解的,有问题请留言): 依赖:我要盖一座房子,就需要很多的砖,这些专就是盖房子的一个依赖.我要跑一个maven项目,需要各种各样的功能,功能实现的jar包和插件就是我的依赖. 聚合 ...

  5. Linux下mysql安装过程

    到mysql官网下载mysql编译好的二进制安装包,在下载页面Select Platform:选项选择linux-generic,然后把页面拉到底部,64位系统下载Linux - Generic (g ...

  6. SQL点点滴滴_查询类型和索引-转载

    当您考虑是否要对列创建索引时, 请估计在查询中使用列的方式, 下表介绍了索引对其有用的查询类型. 表中的示例基于 AdventureWorks2008R2 示例数据库, 在 SQL Server Ma ...

  7. linux oom-killer

    本人从事UTM的开发工作,最近遇到out of memory killer.这里整理一下资料. 简述 当系统内存不足时,系统会触发 oom-killer.oom-killer的机制就是选择杀掉最适合的 ...

  8. ps cs6破解补丁使用方法

    第一步.首先下载ps cs6破解补丁 ,再下载官方ps cs6中文版,安装之后运行一次.第二步.先备份你想要激活的软件的“amtlib”文件,比如PS CS6 64bit其目录在“C:\Program ...

  9. 【设计模式最终总结】桥接模式 VS 外观模式

    差异点 外观模式,是把功能通过一个接口提供出来,方便日后更换实现,或者这种实现可以由多方提供,但同时只用一个.典型例子:@Slf4j 桥接模式,多个维度,每个维度提供一个接口,这些接口集中在一个类中, ...

  10. PHP------关于字符串的处理

    每一种语言对,字符串都是比较重要的,因为字符串牵扯到输出. 尤其是在网页里面,所有的内容输出,都要以字符串的形式展示在页面上.比如,输出换行.输出一段话或者输出一个标签,都是以字符串来输出的:有时用数 ...