我想在我的java程序中表示this file。
我想要做的是快速搜索“key”值,例如,给定值P26
我想要返回spouse
。
也许我可以使用gson作为HashMap
阅读,就像我使用this程序一样。
但是如何应对这种不稳定的结构:
{
"properties": {
"P6": "head of government",
"P7": "brother",
...
我怎样才能很好地融入HashMap
? HashMap
甚至是最佳选择吗?
我把它简化为:
{
"P6": "head of government",
"P7": "brother",
"P9": "sister",
"P10": "video",
"P14": "highway marker",
"P15": "road map",
"P16": "highway system",
"P17": "country",
"P18": "image",
我尝试使用此代码,但输出null
/*
* P values file
*/
String jsonTxt_P = null;
File P_Value_file = new File("properties-es.json");
//read in the P values
if (P_Value_file.exists())
{
InputStream is = new FileInputStream("properties-es.json");
jsonTxt_P = IOUtils.toString(is);
}
Gson gson = new Gson();
Type stringStringMap = new TypeToken<Map<String, String>>(){}.getType();
Map<String,String> map = gson.fromJson(jsonTxt_P, stringStringMap);
System.out.println(map);
答案 0 :(得分:1)
它不起作用,因为该文件不是Map<String, String>
。它有一个属性元素,它包含一个映射,以及一个包含数组的缺少元素。这种不匹配将导致Json返回null,这正是您所看到的。相反,尝试这样做:
public class MyData {
Map<String, String> properties;
List<String> missing;
}
然后,要反序列化,请执行:
MyData data = gson.fromJson(jsonTxt_P, MyData.class);
Map<String, String> stringStringMap = data.properties;
这将使数据结构与json的结构相匹配,并允许json正确反序列化。