无法在Java中将JSON数组转换为列表

hrysbysz  于 2023-08-08  发布在  Java
关注(0)|答案(2)|浏览(123)

我在使用JacksonObject Mapper将JSONArray转换为List时遇到了一个问题。

public class Main {

public static void main(String[] args) throws Exception {
    String test = Files.readString(Path.of("test.json"));
    callRequired(test);
}

public static void callRequired(String test) {
    ObjectMapper mapper = new ObjectMapper();
    try {
        List<Condition> result = mapper.readerForListOf(Condition.class).readValue(test.trim());
        System.out.println(result);
    } catch (JsonMappingException e) {
        e.printStackTrace();
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }
}

字符串
}
test.json是:

{
    "condition": [
        {
            "type": "NONE",
            "subConditons": [
                {
                    "type": "NONE",
                    "subConditions": []
                },
                {
                    "type": "AND",
                    "subConditions": [
                        {
                            "type": "NONE",
                            "subConditions": []
                        }
                    ]
                }
            ]
        },
        {
            "type": "OR",
            "subConditions": []
        }
    ]
}


条件类如下所示:

public class Condition {
Type type = Type.NONE;
List<Condition> subConditions;

public Condition() {
    
}

public Condition(Type type, List<Condition> subConditions) {
    this.type = type;
    this.subConditions = subConditions;
}

public List<Condition> getSubConditions() {
    return subConditions;
}

public void setSubConditions(List<Condition> subConditions) {
    this.subConditions = subConditions;
}

public Type getType() {
    return type;
}

public void setType(Type type) {
    this.type = type;
}

public enum Type {
    NONE,
    AND,
    OR;
}

@Override
public String toString() {
    return "Condition [type=" + type + ", subConditions=" + subConditions + "]";
    }
}

编辑:Condition数组包含一个条件列表,其中有一个subCondition(也是Condition的一种类型)。
**编辑:**谢谢,我已经添加了必要的括号,并检查了它的有效性。我还添加了一个all args构造函数和一个no args构造函数。
如何更改JSON,以便收到包含Jackson嵌套的适当子条件的条件列表。

dzhpxtsq

dzhpxtsq1#

在JSON中,“condition”对象以“[”开头,将其类型设置为数组。这不是条件对象类的样子。
它应该更像:

[
    {
        "type" : "NONE",
        "subConditions" : []
    }
]

字符串

new9mtju

new9mtju2#

如果你不反对切换到 Gson,下面是一个基本的解析。

String test = Files.readString(Path.of("test.json"));
Gson gson = new Gson();
JsonElement element = gson.fromJson(test, JsonObject.class).get("condition");
List<Condition> conditions = Arrays.asList(gson.fromJson(element, Condition[].class));

个字符
产出

(NONE, [(NONE, []), (AND, [(NONE, [])])])
(OR, [])

相关问题