简体   繁体   English

如何解析响应的 json 表示?

[英]How can I parse a json representation of a response?

I'm pretty new to JAVA so my apologies for asking a rather elementary question.我对 JAVA 很陌生,所以我很抱歉问了一个相当基本的问题。

I have a json string that looks like this.我有一个看起来像这样的 json 字符串。

{"statusCode":201,
 "body":"[[\"food_corn\",\"48\"],[\"food_potatoes\",\"130\"],[\"food_rice\",\"80\"]]",
 "headers":{"Access-Control-Allow-Origin":"*"}}

I'm only interested in the body of the text which may have any number of elements.我只对可能包含任意数量元素的文本正文感兴趣。

At the end I'd like to have a map with the item name as the key and the number as the correspond value (as an integer).最后,我想要一个map ,其中项目名称作为键,数字作为对应值(作为整数)。

Thanks for the help!谢谢您的帮助!


Update on where I'm at更新我在哪里

String decoded = new String(invoke.getPayload().array(), "UTF-8");
HashMap<String, Object> map = new ObjectMapper().readValue(decoded, HashMap.class);
Object body = map.get("body")

where body looks like this身体看起来像这样

[["food_corn","48"],["food_potatoes","130"],["food_rice","80"],["food_wheat","999"]]

So then I try parsing it into an array like so所以然后我尝试将它解析成这样的数组

JSONArray array = new JSONArray(body);

But I get the error但我得到了错误

EXCEPTION: JSONArray initial value should be a string or collection or array.

Which doesn't make sensee to me because the above looks like an array of arrays, no?这对我来说没有意义,因为上面看起来像一个 arrays 数组,不是吗?

 @SneakyThrows
 @Test
 public void covertTest() {
  String str = "{\"statusCode\":201,\"body\":\"[[\\\"food_corn\\\",\\\"48\\\"],[\\\"food_potatoes\\\",\\\"130\\\"],"
    + "[\\\"food_rice\\\",\\\"80\\\"]]\",\"headers\":{\"Access-Control-Allow-Origin\":\"*\"}}";
  Map map = objectMapper.readValue(str, Map.class);
  System.out.println(map);
//{statusCode=201, body=[["food_corn","48"],["food_potatoes","130"],["food_rice","80"]], headers={Access-Control-Allow-Origin=*}}
}

Parsing json to obj is called deserialization.将 json 解析为 obj 称为反序列化。 You need to use some libarary to do this.您需要使用一些库来执行此操作。 I recommend Jackson.我推荐 Jackson。 https://github.com/FasterXML/jackson https://github.com/FasterXML/jackson

The below code is a sample to deserialize json into an object of a class.下面的代码是将 json 反序列化为 class 的 object 的示例。 You need to define a class with all the fields then it will create an object of that class mapping to the json data.您需要使用所有字段定义一个 class 然后它将创建一个 object 映射到 Z466DEEC76ECDF324454 数据的 class。

    public void deserializeData() {
      var mapper = new ObjectMapper();
      var json = "{\"statusCode\":201,
     "body":"[[\"food_corn\",\"48\"],[\"food_potatoes\",\"130\"],[\"food_rice\",\"80\"]]",
     "headers":{"Access-Control-Allow-Origin":"*"}}";
      var throwable = catchThrowable(() -> mapper.readValue(json, JSONBody.class));
      log.info("You need to use an empty constructor: {}", throwable.getMessage());
      assertThat(throwable).isInstanceOf(InvalidDefinitionException.class);
    }

Got it to work.让它工作。 Here's how I did it in case it helps anyone in the future.以下是我的做法,以防将来对任何人有所帮助。

(The invoke variable is the response from invoking a lambda call form a lambda call within the same region.) invoke变量是从同一区域内的 lambda 调用中调用 lambda 调用的响应。)

try {
     String decoded = new String(invoke.getPayload().array(), "UTF-8");
     HashMap<String, Object> map = new ObjectMapper().readValue(decoded, HashMap.class);
     String body = map.get("body").toString();
     JSONArray array = new JSONArray(body);

     Map<String, Integer> inventory = new HashMap<>();
     for (Integer i=0; i < array.length(); i++) {
         JSONArray tuple = array.getJSONArray(i);
         String itemName = tuple.getString(0);
         Integer itemCount = tuple.getInt(1);
         inventory.put(itemName, itemCount);
     }
     logger.log("COMPILED INVENTORY: "+inventory.toString()+"\n");
} catch (Exception e) {
     logger.log("EXCEPTION: "+e.getMessage()+"\n");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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