fastjson在把字符串解析成Json对象时,可以通过指定Feature.OrderedField来使Json对象中的元素按字符串中的顺序排列。
但在把字符串解析成JsonArray时好像没有这样的参数可以设置。
在查看源码后发现JSONArray.parseArray内部调用了new JSONObject(lexer.isEnabled(Feature.OrderedField))
public final boolean isEnabled(Feature feature) {
return isEnabled(feature.mask);
}
public final boolean isEnabled(int feature) {
return (this.features & feature) != 0;
}
这里的this.features实际就是JSON.DEFAULT_PARSER_FEATURE
废话少说,上代码:
public static void main(String[] args) {
String str = "{\"b\":321,\"a\":123}";
JSONObject json = JSONObject.parseObject(str);
System.out.println(json);//结果为:{"a":123,"b":321}
JSONObject json2 = JSONObject.parseObject(str, Feature.OrderedField);
System.out.println(json2);//结果为:{"b":321,"a":123}
String arrStr = "[{\"b\":321,\"a\":123}]";
JSONArray array = JSONArray.parseArray(arrStr);
System.out.println(array);//结果为:[{"a":123,"b":321}]
int temp = JSON.DEFAULT_PARSER_FEATURE;
JSON.DEFAULT_PARSER_FEATURE = Feature.config(JSON.DEFAULT_PARSER_FEATURE, Feature.OrderedField, true);
JSONArray array2 = JSONArray.parseArray(arrStr);
JSON.DEFAULT_PARSER_FEATURE = temp;
System.out.println(array2);//结果为:[{"b":321,"a":123}]
}
说明:
如果没有设置Feature.OrderedField则json对象中的元素按字典顺序排列,
如果设置了Feature.OrderedField则按字符串中的顺序排列。
JSON.DEFAULT_PARSER_FEATURE是全局的,如果不希望影响其他功能,建议在完成字符串解析后再把JSON.DEFAULT_PARSER_FEATURE设置为默认值。
这应该只是一种解决方式,如果你有其他的方式,欢迎留言。
如果文章有什么不正确的地方,欢迎指出,我会第一时间改正。
原文:https://www.cnblogs.com/binary-tree/p/10626890.html