I am trying to parse my JSON string using GSON and extract key:value pairs from a simple json string and load it in the map. As of now I am using org.json.simple.parser.JSONParser
to do that. Now I am trying to do the same thing using GSON.
Below is my json string jsonstringA
-
{"description":"Hello World.","hostname":"abc1029.dc3.host.com","ipaddress":"100.671.1921.219","hostid":"/tt/rt/v2/dc3/111","file_timestamp":"20140724","software_version":"v13","commit_hash":"abcdefg"}
Now I need to serialize the above JSON string and extract below fields from json stringg and put it in the map m
as key value pair. Meaning in the map it should be description
as key and Hello World
as the value. Similarly for others as well.
public static final Set<String> MAPPING_FIELDS = new HashSet<String>(Arrays.asList(
"description", "hostname", "ipaddress", "hostid", "software_version"));
private final static JSONParser parser = new JSONParser();
parseJSONData(jsonstringA, MAPPING_FIELDS);
public Map<String, String> parseJSONData(String jsonStr, Set<String> listOfFields) {
Map<String, String> m = new HashMap<String, String>();
try {
Object obj = parser.parse(jsonStr);
org.json.simple.JSONObject jsonObject = (org.json.simple.JSONObject) obj;
if (jsonObject != null) {
for (String field : listOfFields) {
String value = (String) jsonObject.get(field);
m.put(field, value);
}
}
} catch (ParseException e) {
// log exception here
}
return m;
}
How do I use GSON here to do the same thing?