业务场景:对前端传过的json字符串进行转换处理,但是在转换为对象时突然发现发生了乱序,不是进来的时候的顺序了,需要进行更正,保持顺序一致不变。
元数据json字符串是这样的:
"
{
"38b3794634c143ff88aa533ead0ec0b7":"good",
"2f0811da29c54b41988d6e5d173db3d4":"fair",
"5b16c7633c5f47e3bec17d64b2d2f7af":"fair",
"e11296e23ac54e48b1f8f879687b190d":"fair",
"14f3886902204720b758f774365e6043":"fair",
"93ba82a3e44f4904aee164e777b1a0f9":"fair",
"b56ed838bf62490399f9beef5895801e":"fair",
"7f9bd8dee225444198dfba8e4414b4f0":"fair",
"fff63e3f7e5a462d9f64bd1f9cf71460":"fair",
"34002853f0224774884f2ae98e3f0c1a":"fair"
}
"
但是 Map<String,Object> algoMap = JSON.parseObject(algoJsonStr[0])转换后变成了
{
"b56ed838bf62490399f9beef5895801e":"fair",
"7f9bd8dee225444198dfba8e4414b4f0":"fair",
"38b3794634c143ff88aa533ead0ec0b7":"good",
"2f0811da29c54b41988d6e5d173db3d4":"fair",
"5b16c7633c5f47e3bec17d64b2d2f7af":"fair",
"e11296e23ac54e48b1f8f879687b190d":"fair",
"14f3886902204720b758f774365e6043":"fair",
"93ba82a3e44f4904aee164e777b1a0f9":"fair",
"fff63e3f7e5a462d9f64bd1f9cf71460":"fair",
"34002853f0224774884f2ae98e3f0c1a":"fair"
}
如果对顺序没有特殊要求,其实是没事儿的,但是业务必须要知道good的index位置,因此就提出了对json转换,不能改变顺序的要求。
解决方法:
<fastjson.version>1.2.9</fastjson.version>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
fastjson版本必须支持,刚开始用的是1.1.40版本不支持Feature特性
然后对刚开始的代码换成
Map<String,Object> algoMap = JSON.parseObject(algoJsonStr[0],LinkedHashMap.class, Feature.OrderedField);
转换后的效果
{
"38b3794634c143ff88aa533ead0ec0b7":"good",
"2f0811da29c54b41988d6e5d173db3d4":"fair",
"5b16c7633c5f47e3bec17d64b2d2f7af":"fair",
"e11296e23ac54e48b1f8f879687b190d":"fair",
"14f3886902204720b758f774365e6043":"fair",
"93ba82a3e44f4904aee164e777b1a0f9":"fair",
"fff63e3f7e5a462d9f64bd1f9cf71460":"fair",
"34002853f0224774884f2ae98e3f0c1a":"fair"
}