This commit is contained in:
Looly 2024-10-01 00:09:02 +08:00
parent 3a54cc9445
commit 7bdec92d8b
2 changed files with 25 additions and 21 deletions

View File

@ -81,6 +81,24 @@ public class IterTypeAdapter implements MatcherJSONSerializer<Object>, MatcherJS
return deserialize(json, collectionClass, elementType);
}
/**
* 从Iterator中读取数据并添加到JSONArray中
*
* @param source 源对象用于检查循环引用
* @param iter {@link Iterator}
* @param jsonArray {@link JSONArray}
*/
public void mapFromIterator(final Object source, final Iterator<?> iter, final JSONArray jsonArray) {
Object next;
while (iter.hasNext()) {
next = iter.next();
// 检查循环引用
if (next != source) {
jsonArray.addObj(next);
}
}
}
/**
* 反序列化
*
@ -101,23 +119,6 @@ public class IterTypeAdapter implements MatcherJSONSerializer<Object>, MatcherJS
return result;
}
/**
* 从Iterator中读取数据并添加到JSONArray中
*
* @param iter {@link Iterator}
* @param jsonArray {@link JSONArray}
*/
private void mapFromIterator(final Object source, final Iterator<?> iter, final JSONArray jsonArray) {
Object next;
while (iter.hasNext()) {
next = iter.next();
// 检查循环引用
if (next != source) {
jsonArray.addObj(next);
}
}
}
/**
* 将JSONObject转换为集合
*

View File

@ -16,7 +16,7 @@
package org.dromara.hutool.json.serializer.impl;
import org.dromara.hutool.core.convert.CompositeConverter;
import org.dromara.hutool.core.convert.ConvertUtil;
import org.dromara.hutool.core.map.MapUtil;
import org.dromara.hutool.core.reflect.TypeUtil;
import org.dromara.hutool.core.text.StrUtil;
@ -62,8 +62,10 @@ public class MapTypeAdapter implements MatcherJSONSerializer<Map<?, ?>>, Matcher
@Override
public JSON serialize(final Map<?, ?> bean, final JSONContext context) {
final JSON contextJson = context.getContextJson();
// 序列化为JSONArray
if(context.getContextJson() instanceof JSONArray){
if(contextJson instanceof JSONArray){
final Iterator<?> iter;
if(bean instanceof Iterator){
iter = (Iterator<?>) bean;
@ -72,7 +74,8 @@ public class MapTypeAdapter implements MatcherJSONSerializer<Map<?, ?>>, Matcher
} else{
iter = bean.entrySet().iterator();
}
return IterTypeAdapter.INSTANCE.serialize(bean, context);
IterTypeAdapter.INSTANCE.mapFromIterator(bean, iter, (JSONArray) contextJson);
return contextJson;
}
// Map to JSONObject
@ -94,7 +97,7 @@ public class MapTypeAdapter implements MatcherJSONSerializer<Map<?, ?>>, Matcher
for (final Map.Entry<String, JSON> entry : (JSONObject) json) {
map.put(
// key类型为String转目标类型使用标准转换器
CompositeConverter.getInstance().convert(keyType, entry.getKey()),
ConvertUtil.convert(keyType, entry.getKey()),
ObjUtil.apply(entry.getValue(), (value)-> value.toBean(valueType))
);
}