【问题标题】:how to parse json where key is variable using scala play json reader?如何使用scala play json阅读器解析key是可变的json?
【发布时间】:2020-05-29 04:15:50
【问题描述】:

如何访问 i4x-IITB-CS101-problem-33e4aac93dc84f368c93b1d08fa984fc_2_1 密钥和此密钥中的数据?我从未见过一个示例 json 阅读器,它描述了当 key 属性是变量时阅读器如何工作,如下例所示。

{
    "username": "batista",        
    "event_type": "problem_check",      
    "ip": "127.0.0.1",
    "event": {
        "submission": {
            "i4x-IITB-CS101-problem-33e4aac93dc84f368c93b1d08fa984fc_2_1": {
                "input_type": "choicegroup",
                "question": "",
                "response_type": "multiplechoiceresponse",
                "answer": "MenuInflater.inflate()",
                "variant": "",
                "correct": true
            }
        },
        "success": "correct",
        "grade": 1,
        "correct_map": {
            "i4x-IITB-CS101-problem-33e4aac93dc84f368c93b1d08fa984fc_2_1": {
                "hint": "",
                "hintmode": null,
                "correctness": "correct",
                "npoints": null,
                "msg": "",
                "queuestate": null
            }
        }

【问题讨论】:

    标签: scala playframework jsonreader


    【解决方案1】:

    您可以将它们反序列化为 MapString 键和值,这些键和值由您为其编写 JSON 阅读器的类定义。 Play JSON 包含一个built-in reader for Map types

    【讨论】:

      【解决方案2】:

      您可以使用迭代器。不知道您的 json 的确切结构以及它的灵活性,但您可以通过这段 Java 代码了解。

      JsonNode events = jsonOutput.get("event");
      for (Iterator<JsonNode> it = invoices.iterator(); it.hasNext(); ){
          // With this line you will get submission, success, grade and correct_map.
          JsonNode node = it.next();
      
          // if e.g. submission always has one element it is accessible through node.get(0),
          // you may also iterate through e.g. node.elements()
      }
      

      【讨论】:

      • 显然,自从投反对票以来,我没有给你想要的答案。如果您能详细说明您的需求,我可以尽力提供帮助。
      猜你喜欢
      • 1970-01-01
      • 2016-07-12
      • 2021-05-13
      • 2018-05-29
      • 1970-01-01
      • 1970-01-01
      • 2021-09-28
      • 2015-07-26
      • 2023-03-16
      相关资源
      最近更新 更多