我已经尝试搜索这个主题两天了,但没有找到答案。对于这个话题,感觉就像大海捞针一样。
我正在尝试解析 JSONArray,以便将值放入 String[] 中,这样我就可以获得单词及其定义的映射。
我在 IntelliJ 上使用 Java 和 json-simple。
我的 JSON 文件具有以下格式:
{
"word 1": ["Definition 1.", "Definition 2.", "Definition 3."],
"word 2": ["Definition includes \"quotes\"."]
}
我可以理解这个词没有问题,但定义却造成了麻烦。到目前为止,我所能得到的只是上面显示的原始定义字符串。
例如:
word 2
["Definition includes \"quotes\"."]
我发现一个资源似乎具有类似的 JSON 结构。我还看到了这个帖子。我根据这些例子想出了以下测试。
private void loadJSONDictionary() {
JSONObject jsonDictionary = null;
JSONParser parser = new JSONParser();
try (FileReader reader = new FileReader(this.fileName)) {
jsonDictionary = (JSONObject) parser.parse(reader);
for (Object key : jsonDictionary.keySet()) {
String word = key.toString();
JSONArray definitions = (JSONArray) jsonDictionary.get(key);
for (Object definition : definitions) {
System.out.println(definition.toString());
}
}
}
// catch clauses
}
这给了我一个例外:
class java.lang.String cannot be cast to class org.json.simple.JSONArray
当我尝试投射到JSONArray
时。
我还尝试创建一个
new JSONArray()
并将定义添加到其中,这只是给了我 null
。
从阅读其他帖子来看,我似乎很接近,但无论我尝试什么,我要么得到例外,要么
null
。
有没有办法通过解析将每个单词的定义放入String[]中?显然我对此很陌生。如果有帮助的话,我愿意使用其他 API。
这个库可能已经过时并且有bug,你可以创建一些断点来调试最终的jsonDictionary。对我来说,Gson 或 FastJson 使用更广泛。以下是 Gson 代码的工作示例:
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
public class JsonTest {
public static void main(String[] args) {
String jsonString = "{\n" +
" \"word 1\": [\"Definition 1.\", \"Definition 2.\", \"Definition 3.\"], \n" +
" \"word 2\": [\"Definition includes \\\"quotes\\\".\"]\n" +
"}";
Type empMapType = new TypeToken<Map<String, List<String>>>() {}.getType();
Map<String, List<String>> nameEmployeeMap = new Gson().fromJson(jsonString, empMapType);
for(String key : nameEmployeeMap.keySet()) {
System.out.println("key =" + key);
List<String> value = nameEmployeeMap.get(key);
System.out.println("value =" + value);
for (String v : value) {
System.out.println("v =" + value);
}
}
}
}
输出为:
key =word 1
value =[Definition 1., Definition 2., Definition 3.]
v =[Definition 1., Definition 2., Definition 3.]
v =[Definition 1., Definition 2., Definition 3.]
v =[Definition 1., Definition 2., Definition 3.]
key =word 2
value =[Definition includes "quotes".]
v =[Definition includes "quotes".]
检查 https://www.baeldung.com/gson-json-to-map 了解更多信息。