json 对象属性的输出顺序测试,fastJson 有序,jackson,gson无序(需代码中人工按约定来编码)接口数据签名规则
fastJson会根据对象的字段的首字母来排序。
而jackson,gson是根据对象的类中定义的属性的代码中的先后顺序输出。不会排序。
针对业务场景需要对接口中对象存在集合列表等,需要约定对象中的属性按字母升序来排序,而不是乱序。来做签名和验签。
否则“签名错误”,需要排查签名前和签名后的字符串对比。来发现差异。
package com.example.core.mydemo.json5; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.Gson; import java.util.ArrayList; import java.util.List; /** * 测试券对象 */ public class MyCouponIdObject { private String sex; private Integer orderType; private String couponCode; private String name; public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getName() { return name; } public void setName(String name) { this.name = name; } private static final ObjectMapper MAPPER = new ObjectMapper(); public String getCouponCode() { return couponCode; } public void setCouponCode(String couponCode) { this.couponCode = couponCode; } public Integer getOrderType() { return orderType; } public void setOrderType(Integer orderType) { this.orderType = orderType; } public static void main(String[] args) { MyCouponIdObject c1 = new MyCouponIdObject(); c1.setOrderType(1); c1.setCouponCode("111"); c1.setName("Eric"); c1.setSex("男"); System.out.println("fastJson=" + JSON.toJSONString(c1)); try { System.out.println("jackson=" + MAPPER.writeValueAsString(c1)); } catch (JsonProcessingException e) { e.printStackTrace(); } System.out.println("gson=" + new Gson().toJson(c1)); /** * fastJson={"couponCode":"111","orderType":1} * jackson={"orderType":1,"couponCode":"111"} * gson={"orderType":1,"couponCode":"111"} * * 新增两个字段后 output * fastJson={"couponCode":"111","name":"Eric","orderType":1,"sex":"男"} * jackson={"sex":"男","orderType":1,"couponCode":"111","name":"Eric"} * gson={"sex":"男","orderType":1,"couponCode":"111","name":"Eric"} * 发现:fastJson会根据字段的首字母来排序。 * 而jackson,gson是根据对象的类中定义的属性的先后顺序输出。 */ } }
标签:fastJson,jackson,String,couponCode,orderType,gson,json,public From: https://www.cnblogs.com/oktokeep/p/17793630.html