Closed duyucongc closed 2 months ago
正常情况下空数组会返回一个 [],而不是{}
@duyucongc 自定义一个ObjectReader。
@JSONField(deserializeUsing = MyListReader.class)
public void setList(List
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 跟一下源码。
谢谢感谢~
因为遇到一些接口的某些字段的,正常情况下是一个数组,但是当空的时候,会直接返回一个空对象,想问一下,现在有什么好的接受办法么 比如 正常情况下是 {"array":["1","2"]} 空的情况下会直接返回 {"array":{}} 如果我的对象是 class TestArray { private List array;
}