0

我提出了一个 Unirest 请求,并以 JsonNode 的形式获得了响应,并试图将其转换为 Map<String, Boolean>,但到目前为止没有任何效果。到目前为止,这是我尝试过的几件事:

  1. 使用对象映射器
ObjectMapper mapper = new ObjectMapper();
Map<String, Boolean> responseMap = mapper.convertValue(myJsonNode, new TypeReference<Map<String, Boolean>>(){});

但是,当我稍后迭代它时,这给了我以下错误:java.lang.IllegalArgumentException: No serializer found for class org.json.JSONObject and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: com.mashape.unirest.http.JsonNode["array"])

  1. 使用 Gson
JSONObject jsonObject = myJsonNode.getObject(); 
HashMap<String,Boolean> responseMap = new Gson().fromJson(jsonObject.toString(),HashMap.class);

但是,这给了我解析错误:java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Boolean但是,即使我将其更改为字符串而不是布尔值,它也会告诉我我无法将布尔值转换为字符串????诡异的。

  1. 将 JsonNode 转换为 String 然后是 Map:

字符串 myJson = pocoResponseJson.toString(); ObjectMapper 映射器 = 新 ObjectMapper(); 地图<字符串,字符串> responseMap = null; responseMap = mapper.readValue(myJson, Map.class);

然而,这仍然给了我这个错误java.lang.ClassCastException: java.lang.Boolean cannot be cast to java.lang.String,因为来自 HTTP 响应的映射值是一个布尔值。

我对任何一种方法都很好,我会做任何有效的事情提前谢谢你!

4

0 回答 0