fastjson 字段位置被交换

mcdcgff0  于 2021-11-27  发布在  Java
关注(0)|答案(6)|浏览(281)

String json = "{"apiName":"template.loadAll","param":{"name":"张三","age":"12"},"callbacks":""}";

public class InjectedBean {
private String apiName;
private String param;
private String callbacks;

public String getApiName() {
    return apiName;
}

public void setApiName(String apiName) {
    this.apiName = apiName;
}

public String getParam() {
    return param;
}

public void setParam(String param) {
    this.param = param;
}

public String getCallbacks() {
    return callbacks;
}

public void setCallbacks(String callbacks) {
    this.callbacks = callbacks;
}

}

InjectedBean parseObject = JSON.parseObject(json,InjectedBean.class);
System.out.println(parseObject.getParam());

输出结果{"age":"12","name":"张三"}
我原本是{"name":"张三","age":"12"}
版本compile 'com.alibaba:fastjson:1.1.58.android'

lhcgjxsq

lhcgjxsq1#

可以试下
InjectedBean parseObject = JSON.parseObject(json,InjectedBean.class,Feature.OrderedField);

k5ifujac

k5ifujac2#

依然被交换了 , 使用非Android版就不会有问题

6kkfgxo0

6kkfgxo03#

看了下Android版本的源码,问题出在

com.alibaba.fastjson.serializer.MapSerializer

Map<?, ?> map = (Map<?, ?>) object;
        Class<?> mapClass = map.getClass();
        boolean containsKey = (mapClass == JSONObject.class || mapClass == HashMap.class || mapClass == LinkedHashMap.class) 
                && map.containsKey(JSON.DEFAULT_TYPE_KEY);

        if ((out.features & SerializerFeature.SortField.mask) != 0) {
            if ((!(map instanceof SortedMap)) && !(map instanceof LinkedHashMap)) {
                try {
                    map = new TreeMap(map);
                } catch (Exception ex) {
                    // skip
                }
            }
        }

传入的object为JSONObject对象里边虽然存的linkedHashMap但是对象本身
if ((!(map instanceof SortedMap)) && !(map instanceof LinkedHashMap)) {
判断为true,所以就把map的顺序搞乱了,不知道是不是bug,在普通版本中这块被注解掉了。

fcipmucu

fcipmucu4#

知道问题源了 , 期望确定一下是不是BUG

hujrc8aj

hujrc8aj5#

是这样设计的,不是bug

scyqe7ek

scyqe7ek6#

有可能提供一种配置让位置不要交换呢

相关问题