简体   繁体   中英

how to parse json where key is variable using scala play json reader?

how can i access i4x-IITB-CS101-problem-33e4aac93dc84f368c93b1d08fa984fc_2_1 key and data inside this key? I have never seen an example json reader that describes how the reader works when the key attribute is a variable such as below example.

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

You can deserialize these as a Map with String keys and values defined by a class that you have written a JSON reader for. Play JSON includes a built-in reader for Map types .

You may use an iterator. Don't know the exact structure of your json and how flexible it is, but you get the idea with this Java code.

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()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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