Skip to content

array_to_map_cn

Shaojin Wen edited this page Jul 15, 2024 · 5 revisions

JSONField支持配置arrayToMapKey,支持将JSON数组映射到Map类型字段

当我们的输入JSON是一个数组,但字段类型是Map,如下的场景:

{
    "functions":[
        {"name": "concat", "category": ["Array","String"]},
        {"name": "count",  "category": "aggregate"},
        {"name": "count",  "category": "window"}
    ]
}

希望反序列化的Java对象结构如下:

public static class Bean3 {
    public final Map<String, Function> functions = new LinkedHashMap<>();
}


public static class Function {
    public String name;
    public final Set<Category> category = new LinkedHashSet<>();
}

 public enum Category {
        Array,
        Aggregate,
        Window,
        Numeric,
        String,
        Datetime
    }
}

FASTJSON2在2.0.52版本之后,提供了一个快捷的配置方式,能简化处理代码,如下:

public static class Bean3 {
    // 这里配置需要,当反序列化输入JSONArray时,会用JSONArray中的每个元素的Key当做Map的Key来构造Map
    @JSONField(arrayToMapKey = "name")
    public final Map<String, Function> functions = new LinkedHashMap<>();
}

当需要处理重复时,则可以这样

public static class Bean3 {
    // arrayToMapDuplicateHandler配置重复处理器,需要是BiConsumer的派生类
    @JSONField(arrayToMapKey = "name", arrayToMapDuplicateHandler = FunctionDuplicateHandler.class)
    public final Map<String, Function> functions = new LinkedHashMap<>();
}

static class FunctionDuplicateHandler
        implements BiConsumer<Function, Function> {
    @Override
    public void accept(Function origin, Function newItem) {
        origin.category.addAll(newItem.category);
    }
}