sarma senagavaram sarma senagavaram - 4 months ago 11
reST (reStructuredText) Question

how to get json keys when im getting the json content in string format?

Im getting my json in string format from the URI .

String srvdiagJson = getJsonFromHttpConnection(diagcon);


my json data looks like this.

{"hdd_errors":18446744073709552000,"vnet2_tx_packets":86647,"vnet2_rx":19753895921,"vda_write":2873672704,"hdd_read":180702,"vnet2_tx":15722682,"vnet2_rx_drop":691,"vnet2_rx_errors":0,"memory-swap_in":0,"hdd_read_req":78,"vnet2_tx_drop":0,"vnet2_tx_errors":0,"hdd_write":0,"memory":2097152,"memory-rss":1598552,"cpu0_time":48668260000000,"vda_read":251817472,"vda_write_req":267405,"vnet2_rx_packets":225351039,"memory-actual":2097152,"hdd_write_req":0,"vda_read_req":16222,"vda_errors":18446744073709552000}


I think there is no need of parsing the data.But i also tried parsing it on advice and kept it in both object and array. but i am unable to access any values.

Answer

Using Jackson? You could try one of the following approaches to get the keys from your JSON:

Parsing JSON into a JsonNode

ObjectMapper mapper = new ObjectMapper();

JsonNode root = mapper.readTree(json);

Iterator<String> it = root.fieldNames();
while (it.hasNext()){
    System.out.println(it.next());
}

Parsing JSON into a Map<String, Object>

ObjectMapper mapper = new ObjectMapper();

TypeReference<LinkedHashMap<String, Object>> typeReference 
    = new TypeReference<LinkedHashMap<String, Object>>() {};
Map<String, Object> root = mapper.readValue(json, typeReference);

root.keySet().forEach(System.out::println);

Both solutions require jackson-databind dependency.