4

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?

0

1 Answer 1

8

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

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

Hope it helps! :)

Sign up to request clarification or add additional context in comments.

1 Comment

No problem, it happens. Feel free to accept my answer :P

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.