gson 使用Jackson将JSON数组反序列化为Java对象(既不是列表也不是集合

cld4siwp  于 2023-02-04  发布在  Java
关注(0)|答案(1)|浏览(145)

我之前使用的是Gson,出于实际原因决定转移到Jackson。之前,我有一个JSON反序列化器,它正在将JSON对象的数组反序列化为单个Java对象。
字段的json结构为:

{
    id: number,
    type: (0 | 1),
    allow: number,
    deny: number
}[]

我需要将这个数组反序列化为我自己的对象:PermissionOverwrites.
以前,我在Gson中使用了以下代码:

JsonArray array = json.getAsJsonArray();
Map<Permissionable, Permissions> map = new HashMap<>();
 
for (JsonElement element : array) {
    JsonObject object = element.getAsJsonObject();
    Permissionable p = switch (object.get("type").getAsInt()) {
        case 0 -> new Permissionable.MockPermissionable(object.get("id").getAsLong()); 
        case 1 -> new Permissionable.MockPermissionable(object.get("id").getAsLong()); 
        default -> throw new JsonParseException("Unknown permissionable type");
    };
    Permissions perms = new Permissions(object.get("allow").getAsLong(), object.get("deny").getAsLong());
    map.put(p, perms);
}
 
return new PermissionOverwrites(map);

但是现在,使用Jackson,我有一个JsonParser和一个DeserializationContext,但是我在这两个文件中找不到任何东西来解析一个ArrayNode,你知道我可以用Jackson做什么吗?
先谢谢你!
编辑:
PermissionsOverwrites.java

@ToString
@EqualsAndHashCode
public class PermissionOverwrites {

    private Map<Permissionable, Permissions> overwrites;
    
    public PermissionOverwrites(Map<Permissionable, Permissions> overwrites) {
        this.overwrites = overwrites;
    }
    
    public PermissionOverwrites() {
        this.overwrites = new HashMap<>();
    }
    
    public Map<Permissionable, Permissions> getOverwrites() {
        return Collections.unmodifiableMap(overwrites);
    }
    
}

JSON对象的示例:

[
    {
        "id": "111111111111111111",
        "type": "0",
        "allow": "01010",
        "deny": "10101"
    }
],
jecbmhm3

jecbmhm31#

此代码使用Jackson执行与使用Gson的代码相同的操作:

JsonNode array = mapper.readTree(json);
for (JsonNode element : array) {
  Map<Permissionable, Permissions> map = new HashMap<>();
  Permissionable p = switch (element.get("type").asInt()) {
    case 0 -> new Permissionable.MockPermissionable(element.get("id").asLong());
    case 1 -> new Permissionable.MockPermissionable(element.get("id").asLong());
    default -> throw new JsonParseException("Unknown permissionable type", null);
  };
  Permissions perms = new Permissions(element.get("allow").asLong(), element.get("deny").asLong());
  map.put(p, perms);
}

return new PermissionOverwrites(map);

这是an article about how to work with Jackson JSON tree model

相关问题