简体   繁体   中英

How to serialize json string using GSON and extract key and value from it?

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?

It's very simple. Just create a POJO that have same variable as used in JSON string.

Have a look in Java Doc of Gson#fromJson(Reader,Type)

sample code:

class ClientDetail {
    private String description;
    private String hostname;
    private String ipaddress;
    private String hostid;
    private String file_timestamp;;
    private String software_version;
    private String commit_hash;
    // getter & setter
}

BufferedReader reader = new BufferedReader(new FileReader(new File("json.txt")));
ClientDetail data = new Gson().fromJson(reader, ClientDetail.class);

You can convert it into Map as well using TypeToken to convert it into expected type.

sample code:

BufferedReader reader = new BufferedReader(new FileReader(new File("json.txt")));
Type type = new TypeToken<Map<String, String>>() {}.getType();
Map<String, String> data = new Gson().fromJson(reader, type);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM