Present a JSON file in a java program for requesting values ​​by key

I want to present this file in my java program.

What I want to do is quickly search by the value of "key", so, for example, given the value of P26 , I would like to return spouse .

Maybe I can read it as a HashMap using gson, as it was in this program.

But what to do with this awkward structure:

 { "properties": { "P6": "head of government", "P7": "brother", ... 

How could I fit well in a HashMap ? Is HashMap best choice?


I simplified this a bit:

 { "P6": "head of government", "P7": "brother", "P9": "sister", "P10": "video", "P14": "highway marker", "P15": "road map", "P16": "highway system", "P17": "country", "P18": "image", 

I tried to use this code, but it outputs 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); 
+5
source share
1 answer

This does not work because this file is not Map<String, String> . it has a property element that contains the mapping and a missing element that contains the array. This mismatch will cause Json to return null, and this is what you see. Instead, try doing this:

 public class MyData { Map<String, String> properties; List<String> missing; } 

And then to deserialize, do:

 MyData data = gson.fromJson(jsonTxt_P, MyData.class); Map<String, String> stringStringMap = data.properties; 

This will cause the data structure to match the json structure and allow json to properly deserialize.

+1
source

All Articles