Java Parse Json Object Containing Map of Strings to Map to Strings to a String Array

时间:2018-12-19 11:39:18

标签: java json jackson

I am trying to parse a json string that is an object that contains a map of string keys to a map of string keys to a string array. I have simplified the json string to just the object that I am struggling to parse but is actually an object embedded within other objects.

Json:

{"restrictions": {
    "master": "bsu.school",
    "conditions": {
        "HCI": [
            "CMP",
            "HRM",
            "PUBL",
            "CRA",
            "FTV",
            "AGS",
            "MAS",
            "MCOM",
            "BMPP",
            "BUS",
            "CUS",
            "FSS",
            "PHET",
            "HIST",
            "ENL",
            "STR",
            "CWR",
            "STAF"
        ],
        "MPA": [
            "MAPE",
            "MAPS",
            "BACC",
            "MASW",
            "BAMU",
            "BAPA",
            "MAPA",
            "MATY",
            "MACM",
            "BADR",
            "KIST",
            "BADA",
            "PARM",
            "BAP",
            "BACM",
            "BATP",
            "MACO",
            "BACMT",
            "CSMT",
            "BAAM"
        ],
        "BSAD": [
            "BSAD3",
            "BSAD1",
            "BSAD2"
        ]
    }
}}

I have created a simple test class to just test parsing this particular object:

import java.io.IOException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonParseTest {

    public static void main(String[] args) {
        String json = "{\"restrictions\":{\"master\":\"bsu.school\",\"conditions\":{\"HCI\":[\"CMP\",\"HRM\",\"PUBL\",\"CRA\",\"FTV\",\"AGS\",\"MAS\",\"MCOM\",\"BMPP\",\"BUS\",\"CUS\",\"FSS\",\"PHET\",\"HIST\",\"ENL\",\"STR\",\"CWR\",\"STAF\"],\"MPA\":[\"MAPE\",\"MAPS\",\"BACC\",\"MASW\",\"BAMU\",\"BAPA\",\"MAPA\",\"MATY\",\"MACM\",\"BADR\",\"KIST\",\"BADA\",\"PARM\",\"BAP\",\"BACM\",\"BATP\",\"MACO\",\"BACMT\",\"CSMT\",\"BAAM\"],\"BSAD\":[\"BSAD3\",\"BSAD1\",\"BSAD2\"]}}}";
        ObjectMapper objectMapper = new ObjectMapper();
        // Convert the json string to Restrictions object
        try {
            RestrictionsContainer restrictionsContainer = objectMapper.readValue(json, RestrictionsContainer.class);
            System.out.println("restrictionsContainer " + restrictionsContainer);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

RestrictionsContainer class:

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown = true)
public class RestrictionsContainer {
    private Restrictions restrictions = null;

    /**
     * @return the restrictions
     */
    public Restrictions getRestrictions() {
        return restrictions;
    }

    /**
     * @param restrictions the restrictions to set
     */
    public void setRestrictions(Restrictions restrictions) {
        this.restrictions = restrictions;
    }

    /* (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("RestrictionsContainer [restrictions=").append(restrictions).append("]");
        return builder.toString();
    }
}

Restrictions class:

import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown = true)
public class Restrictions {
    private String master = null;

    private Map<String, Object> conditions = new HashMap<>();

    /**
     * @return the master
     */
    public String getMaster() {
        return master;
    }

    /**
     * @param master the master to set
     */
    public void setMaster(String master) {
        this.master = master;
    }

    /**
     * @return the conditions
     */
    public Map<String, Object> getConditions() {
        return conditions;
    }

    /**
     * @param conditions the conditions to set
     */
    public void setConditions(Map<String, Object> conditions) {
        this.conditions = conditions;
    }

    /* (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("Restrictions [master=").append(master).append(", conditions=").append(conditions).append("]");
        return builder.toString();
    }
}

The code above works when I set the the Conditions to a map of String to Objects but what I really want is to specify what type of objects it is which I think should be:

private Map<String, Map<String,List<String>>> conditions = new HashMap<>();

However, when I use this instead I get the following error message:

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.util.LinkedHashMap` out of START_ARRAY token
 at [Source: (String)"{"restrictions":{"master":"bsu.school","conditions":{"HCI":["CMP","HRM","PUBL","CRA","FTV","AGS","MAS","MCOM","BMPP","BUS","CUS","FSS","PHET","HIST","ENL","STR","CWR","STAF"],"MPA":["MAPE","MAPS","BACC","MASW","BAMU","BAPA","MAPA","MATY","MACM","BADR","KIST","BADA","PARM","BAP","BACM","BATP","MACO","BACMT","CSMT","BAAM"],"BSAD":["BSAD3","BSAD1","BSAD2"]}}}"; line: 1, column: 60] (through reference chain: RestrictionsContainer["restrictions"]->Restrictions["conditions"]->java.util.LinkedHashMap["HCI"])
    at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:63)
    at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1342)
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1138)
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1092)
    at com.fasterxml.jackson.databind.deser.std.StdDeserializer._deserializeFromEmpty(StdDeserializer.java:599)....

The string keys for the conditions object are dynamic so I can't use an object.

What is the correct way to define the conditions object?

2 个答案:

答案 0 :(得分:2)

您定义的conditions类型错误:

private Map<String, Map<String,List<String>>> conditions = new HashMap<>(); // WRONG

实际上,您的json中conditions的类型是:

private Map<String, List<String>> conditions;

更改此设置,您的代码即可正常运行。

答案 1 :(得分:0)

您的代码没有什么问题,而是Jackson不能“直接引用类型”。类型引用返回表示该类表示的实体的直接超类(类,接口,原始类型或void)的Type。 / p>

如果超类是参数化类型,则返回的Type对象必须准确反映源代码中使用的实际类型参数。

您的修补程序应如下所示:

Map<String, Map<String,List<String>>> myObjects = mapper.readValue(mapData , new TypeReference<Map<String, Map<String,List<String>>>(){});