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

201 Views Asked by At

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
            }
        }
2

There are 2 best solutions below

1
Eirik Finvold On

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()
}
0
Tim Moore On

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.