gpt4 book ai didi

java.lang.ClassCastException : class net. sf.json.JSONObject 无法转换为类 net.sf.json.JSONArray

转载 作者:行者123 更新时间:2023-12-01 18:19:43 28 4
gpt4 key购买 nike

我的 JSON 有问题。我的代码中的这一行抛出异常

String jsontxt = IOUtils.toString(new FileInputStream(Filename), "UTF-8");
JSONArray root = (JSONArray) JSONSerializer.toJSON(jsontxt);

jsontxt 是一个存储我所有 JSON 的字符串。

由于某种原因,我有这个异常(exception):

Exception in thread "main" java.lang.ClassCastException: class net.sf.json.JSONObject cannot be cast to class net.sf.json.JSONArray (net.sf.json.JSONObject and net.sf.json.JSONArray are in unnamed module of loader 'app')

我使用 Lint 验证了我的 JSON 文件。知道它可能来自哪里吗?

这是我的 JSON:

{
"numero_de_permis": "A0001",
"cycle": "2018-2020",
"heures_transferees_du_cycle_precedent": 2,
"activites": [{
"description": "Cours sur la déontologie",
"categorie": "cours",
"heures": 14,
"date": "2019-03-20"
},
{
"description": "Séminaire sur l'architecture contemporaine",
"categorie": "séminaire",
"heures": 10,
"date": "2019-01-07"
},
{
"description": "Rédaction pour le magazine Architecture moderne",
"categorie": "rédaction professionnelle",
"heures": 6,
"date": "2019-10-22"
},
{
"description": "Participation à un groupe de discussion sur le partage des projets architecturaux de plus de 20 ans ",
"categorie": "groupe de discussion",
"heures": 6,
"date": "2019-04-01"
},
{
"description": "Visite d'établissements architecturaux",
"categorie": "voyage",
"heures": 2,
"date": "2019-02-02"
}
]
}

jsontxt 的值与我的 jsonfile 相同,这意味着它加载正确:

{
"numero_de_permis": "A0001",
"cycle": "2018-2020",
"heures_transferees_du_cycle_precedent": 2,
"activites": [{
"description": "Cours sur la déontologie",
"categorie": "cours",
"heures": 14,
"date": "2019-03-20"
},
{
"description": "Séminaire sur l'architecture contemporaine",
"categorie": "séminaire",
"heures": 10,
"date": "2019-01-07"
},
{
"description": "Rédaction pour le magazine Architecture moderne",
"categorie": "rédaction professionnelle",
"heures": 6,
"date": "2019-10-22"
},
{
"description": "Participation à un groupe de discussion sur le partage des projets architecturaux de plus de 20 ans ",
"categorie": "groupe de discussion",
"heures": 6,
"date": "2019-04-01"
},
{
"description": "Visite d'établissements architecturaux",
"categorie": "voyage",
"heures": 2,
"date": "2019-02-02"
}
]
}

编辑:我找到了解决问题的方法。感谢 Arnaud Claudel,我注意到我的 JSON 一开始只是一个对象而不是数组。所以这样做修复了我的错误:

JSONObject  root = (JSONObject) JSONSerializer.toJSON(jsontxt);

最佳答案

问题是您有一个 JSON 对象,而不是数组。

因此,您不能将其转换为 JSONArray,而应将其转换为 JSONObject

关于java.lang.ClassCastException : class net. sf.json.JSONObject 无法转换为类 net.sf.json.JSONArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60310109/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com