当我以字符串格式获取json内容时如何获取json密钥?

时间:2016-08-02 06:37:41

标签: java json rest

我从URI中获取字符串格式的json。

String srvdiagJson = getJsonFromHttpConnection(diagcon);

我的json数据看起来像这样。

{"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}

我认为不需要解析数据。但我也尝试在建议中解析它并将其保存在对象和数组中。但我无法访问任何值。

3 个答案:

答案 0 :(得分:0)

您可以使用jackson将json字符串转换为java对象,反之亦然。 e.g

.directive('voteplus', function() {
    return {
        scope: true, // <-- add this
        link: function(scope, element, attrs) {
            element.bind('click', function(e){
                scope.isDisabled = true;
                scope.$apply();
            });
        }
    }
});

答案 1 :(得分:0)

进口:

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

代码段:

ObjectMapper mapper = new ObjectMapper();
try {
    JsonNode jsonNode = mapper.readTree(jsonStr);
    Iterator<String> it = jsonNode.fieldNames();
    while(it.hasNext()){
        System.out.println(it.next()); // Printing JSON KEYS
    }
} catch (JsonProcessingException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

使用Jackson parser

实现解析

答案 2 :(得分:0)

使用杰克逊?您可以尝试以下方法之一从JSON获取密钥:

将JSON解析为JsonNode

ObjectMapper mapper = new ObjectMapper();

JsonNode root = mapper.readTree(json);

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

将JSON解析为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);

两种解决方案都需要jackson-databind依赖。