killQuotes killQuotes - 3 months ago 7
JSON Question

Deserialize JSON object that has no name

We have a rather odd JSON payload that needs to be deserialized, but I'm unsure how to go about doing it with Java and Gson.

{
"Red": {
"Level 1": "Specify Action",
"Level 2": "Action Taken",
"Level 3": "No Action Taken"
},
"Orange": {
"Level 4": "Defeat Gannon",
"Level 5": "Save Princess",
"Level 6": "Find Triforce"
}
}


We can use a HashMap to deserialize the individual objects (i.e. "Red" and "Orange"), but the problem we're having is trying to account for the parent object, which, as the code shows, has no name to easily hook into.

Answer

Considering that your JSON looks like below:

{
    "Red": {
       "Level 1": "Specify Action",
       "Level 2": "Action Taken",
       "Level 3": "No Action Taken"
    },
   "Orange": {
       "Level 4": "Defeat Gannon",
       "Level 5": "Save Princess",
       "Level 6": "Find Triforce"
     }
}

I will use HashMap, something like below with Jackson API. I think similar can be done using GSON as well

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

        import java.io.IOException;
        import java.util.HashMap;
        import java.util.Map;

        public class Test {

            public static void main(String[] args) throws IOException {

                ObjectMapper mapper = new ObjectMapper();
                String jsonInString = "{\n" +
                        "    \"Red\": {\n" +
                        "        \"Level 1\": \"Specify Action\",\n" +
                        "        \"Level 2\": \"Action Taken\",\n" +
                        "        \"Level 3\": \"No Action Taken\"\n" +
                        "    },\n" +
                        "    \"Orange\": {\n" +
                        "        \"Level 4\": \"Defeat Gannon\",\n" +
                        "        \"Level 5\": \"Save Princess\",\n" +
                        "        \"Level 6\": \"Find Triforce\"\n" +
                        "    }\n" +
                        "}";

                TypeReference< Map<String, HashMap<String, String>>> typeRef
                        = new TypeReference<Map<String, HashMap<String, String>>>() {
                };

                Map<String, HashMap<String, String>> value = mapper.readValue(jsonInString, typeRef);

                System.out.println(value);

            }
        }