用jackson将json文件读入HashMap

时间:2016-12-06 12:00:45

标签: java json jackson

我正在尝试将json文件读入java HashMap。 这是我的json文件的内容

{
    "fieldA" : {
        "Preis": "100,00 €",
        "Text_de": "foo",
        "Text_en": "bar",
        "Materialnummer": "32400020"
    },
    "fieldB" : {
        "Preis": "90,00 €",
        "Text_de": "jeha",
        "Text_en": "bla",
        "Materialnummer": "32400030"
    }
}

我的实际问题是,创建的地图为空,我的测试用例中找不到fieldA。但是在读取文件时没有抛出异常。

@Test
public void readJsonFile() throws Exception {
    File inFile = new File(
       getClass().getClassLoader().getResource("doPrefill6_17.json").getFile()
    );
    assertTrue(inFile.exists());
    assertTrue(inFile.canRead());
    Map<String, IpadField> fieldMap = JsonCreator.readJsonFromFile(inFile);
    assertNotNull(fieldMap);
    assertTrue(fieldMap.containsKey("fieldA"));
}

实施

public static Map<String,IpadField> readJsonFromFile(File inFile) throws IOException {
    Map<String, IpadField> map = new HashMap<>();
    ObjectMapper mapper = new ObjectMapper();
    byte[] json = Files.readAllBytes(inFile.toPath());

    mapper.readValue(json, new TypeReference<Map<String, IpadField>>(){});

    return map;

}

这里是POJO

public class IpadField {

    @JsonIgnore
    public String fieldname;
    public String Text_de;
    public String Text_en;
    public String Preis;
    public String Materialnummer;

    public IpadField(){

    }

    @Override
    public String toString() {
        return "IpadField{" +
                "fieldname='" + fieldname + '\'' +
                ", Text_de='" + Text_de + '\'' +
                ", Text_en='" + Text_en + '\'' +
                ", Preis='" + Preis + '\'' +
                ", Materialnummer='" + Materialnummer + '\'' +
                '}';
    }

    public IpadField(String fieldname, String text_de, String text_en, 
        String preis, String materialnummer) {
        this.fieldname = fieldname;
        Text_de = text_de;
        Text_en = text_en;
        Preis = preis;
        Materialnummer = materialnummer;
    }
}

有什么想法吗?

1 个答案:

答案 0 :(得分:7)

您忘记将序列化的值分配给地图。

map = mapper.readValue(json, new TypeReference<Map<String, IpadField>>(){});

希望它有所帮助! :)