json(javascript object notation)
json是一种常见的数据交换的轻量级数据格式。http协议传输数据可以有多种数据格式,比如下面几种常见数据传输格式,除此之外还有其他的数据交换格式。
数据传输类型 | 编码类型 | 示例 |
---|---|---|
表单格式 | application/x-www-form-urlencoded | username=zk&password=123 |
json(javascript object notation) | application/json | {"username": "zk","password": "123"} |
xml(extensible markup language) | application/xml | <user><username>zk</username><password>123</password></user> |
jackson
jackson是一款优秀的json解析库,添加了依赖之后就可以使用对应的注解,让我们能够自由的将java对象和json做转换。
比如java对象转json
@jsonproperty和@jsonfield
为了解决json字符串和其实体bean的属性名匹配不上的问题,@jsonproperty和@jsonfield都可以将某一属性名序列化为另一属性名。
那么@jsonproperty和@jsonfield有什么区别呢?
import com.alibaba.fastjson.json; import com.alibaba.fastjson.annotation.jsonfield; import com.fasterxml.jackson.annotation.jsonproperty; import com.hust.zhang.serializable.jsonutils; import lombok.allargsconstructor; import lombok.builder; import lombok.data; public class jsonpropertiesvsjsonfield { @allargsconstructor @data @builder static class properties { @jsonproperty(value = "json-properties") private string jsonproperties; @jsonfield(name = "json-field") private string jsonfield; } public static void main(string[] args) { properties properties = properties.builder() .jsonproperties("test-properties") .jsonfield("test-field") .build(); system.out.println(jsonutils.tojson(properties)); system.out.println(json.tojsonstring(properties)); } }
输出结果如下,
{"jsonfield":"test-field","json-properties":"test-properties"}
{"json-field":"test-field","jsonproperties":"test-properties"}
可以看到调用jsonutils.tojson方法时,加了@jsonproperty才与bean实际属性名匹配。
其中该方法定义如下,objectmapper的writevalueasstring方法。
/** * json转换工具类 */ @slf4j public final class jsonutils { /** * 私有无参构造方法 常量类不能实例化,直接引用 */ private jsonutils() { } private static final objectmapper object_mapper = new objectmapper(); static { object_mapper.configure(deserializationfeature.fail_on_unknown_properties, false); object_mapper.configure(jsonreadfeature.allow_unescaped_control_chars.mappedfeature(), true); } public static string tojson(object object) { try { return object_mapper.writevalueasstring(object); } catch (jsonprocessingexception e) { log.error("failed to write the object to string" + object.getclass().getname()); return null; } } public static <t>t parse(string json, class<t> tclass){ try { return object_mapper.readvalue(json,tclass); } catch (jsonprocessingexception e) { log.error("failed to deserialize json content, json value : " + json); return null; } } }
除此之外还可以看看@jsonalias
注解。
参考链接
1、https://baijiahao.baidu.com/s?id=1765042798858921947&wfr=spider&for=pc
2、https://developer.aliyun.com/article/768691
到此这篇关于@jsonproperty和@jsonfield注解的区别的文章就介绍到这了,更多相关@jsonproperty和@jsonfield注解内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论