我想在我的java程序中表示这个文件。
我想做的是按"键"值快速搜索它,例如,给定值P26
我想返回spouse
。
也许我可以像使用该程序一样使用 gson 将其作为HashMap
阅读。
但是如何处理这种不稳定的结构:
{
"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);
不起作用,因为该文件不是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 正确反序列化。