alibaba / fastjson

FASTJSON 2.0.x has been released, faster and more secure, recommend you upgrade.
https://github.com/alibaba/fastjson2/wiki/fastjson_1_upgrade_cn
Apache License 2.0
25.73k stars 6.5k forks source link

如果想把空对象序列化为空数组,应该怎么写 #4521

Closed duyucongc closed 2 months ago

duyucongc commented 2 months ago

因为遇到一些接口的某些字段的,正常情况下是一个数组,但是当空的时候,会直接返回一个空对象,想问一下,现在有什么好的接受办法么 比如 正常情况下是 {"array":["1","2"]} 空的情况下会直接返回 {"array":{}} 如果我的对象是 class TestArray { private List array; }

我该怎么写方法才可以接受,有什么预先写好的方法或者自定义写法么
kimmking commented 2 months ago

正常情况下空数组会返回一个 [],而不是{}

xcodemap commented 2 months ago

@duyucongc 自定义一个ObjectReader。 @JSONField(deserializeUsing = MyListReader.class) public void setList(List list) { this.list = list; } public class MyListReader implements ObjectReader {

public MyListReader() {
}

@Override
public Object createInstance(long features) {
    return new ArrayList<>();
}

@Override
public Object createInstance(Collection collection, long features) {
    Collection typedList = (Collection) createInstance(0L);
    for (Object item : collection) {
        if (item == null || item instanceof String) {
            typedList.add(item);
            continue;
        }
        typedList.add(
                JSON.toJSONString(item)
        );
    }
    return typedList;
}

@Override
public Class getObjectClass() {
    return List.class;
}

@Override
public Object readJSONBObject(JSONReader jsonReader, Type fieldType, Object fieldName, long features) {

    if (jsonReader.nextIfNull()) {
        return null;
    }

    int entryCnt = jsonReader.startArray();

    Collection list = new ArrayList();
    for (int i = 0; i < entryCnt; ++i) {
        list.add(jsonReader.readString());
    }

    return list;
}

@Override
public Object readObject(JSONReader jsonReader, Type fieldType, Object fieldName, long features) {
    if (jsonReader.jsonb) {
        return readJSONBObject(jsonReader, fieldType, fieldName, 0);
    }

    if (jsonReader.readIfNull()) {
        return null;
    }

    boolean set = jsonReader.nextIfSet();
    Collection list = set
            ? new HashSet()
            : (Collection) createInstance(jsonReader.getContext().getFeatures() | features);

    char ch = jsonReader.current();
    if (ch == '[') {
        jsonReader.next();
        while (!jsonReader.nextIfArrayEnd()) {
            String item = jsonReader.readString();
            if (item == null && list instanceof SortedSet) {
                continue;
            }
            list.add(item);
        }
    } else if (ch == '"' || ch == '\'' || ch == '{') {
        String str = jsonReader.readString();
        if (str != null && !str.isEmpty()) {
            //list.add(str);
        }
    } else {
        throw new JSONException(jsonReader.info());
    }

    jsonReader.nextIfComma();

    return list;
}

} 亲测上述代码可行,感兴趣可以用 https://xcodemap.tech 跟一下源码。

duyucongc commented 2 months ago

谢谢感谢~