Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading json file into HashMap with jackson

Tags:

java

json

jackson

I am trying to read a json file into a java HashMap. This is the content of my json file

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

My actual problem is, that the created map is empty and fieldA will not be found in my test case. But there is no exception thrown while reading the file.

@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"));
}

The implementation

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;

}

Here the 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;
    }
}

Any idea?

like image 613
Al Phaba Avatar asked Feb 05 '23 14:02

Al Phaba


1 Answers

You forgot to assign the value of the serialization to the map.

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

Hope it helps! :)

like image 150
Turbut Alin Avatar answered Feb 08 '23 04:02

Turbut Alin