表示java程序中的JSON文件,用于按键查询值

5 java json gson

我想在我的java程序中表示这个文件.

我想要做的是快速搜索"key"值,例如,给定P26我想要返回的值spouse.

也许我可以像HashMap使用这个程序一样使用gson 读取它.

但是如何应对这种不稳定的结构:

{
    "properties": {
        "P6": "head of government",
        "P7": "brother",
        ...
Run Code Online (Sandbox Code Playgroud)

我怎么能适应这个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",
Run Code Online (Sandbox Code Playgroud)

我试过使用这个代码,但它输出 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);
Run Code Online (Sandbox Code Playgroud)

dur*_*597 1

它不起作用,因为该文件不是Map<String, String>. 它有一个包含映射的属性元素和一个包含数组的缺失元素。这种不匹配将导致 Json 返回 null,这就是您所看到的。相反,尝试这样做:

public class MyData {
    Map<String, String> properties;
    List<String> missing;
}
Run Code Online (Sandbox Code Playgroud)

然后,要反序列化,请执行以下操作:

MyData data = gson.fromJson(jsonTxt_P, MyData.class);
Map<String, String> stringStringMap = data.properties;
Run Code Online (Sandbox Code Playgroud)

这将使数据结构与json的结构匹配,并允许json正确反序列化。