简体   繁体   中英

Using Jackson to parse Json map value into String or CustomClass

I'm being given a Json file with the form:

{
    "descriptions": {
        "desc1": "someString",
        "desc2": {"name":"someName", "val": 7.0}
    }
}

I have the POJO:

public class CustomClass {
    Map<String, Object> descriptions;
    public static class NameVal{
        String name;
        double val;
        public NameVal(String name, double val){...}
    }
}

I can recreate the json file with the code:

CustomClass a = new CustomClass();
a.descriptions = new HashMap<String, Object>();
a.descriptions.put("desc1", "someString");
a.descriptions.put("desc2", new CustomClass.NameVal("someName", 7.0));
new ObjectMapper().writeValue(new File("testfile"), a);

But, when I read the object back in using:

CustomClass fromFile = new ObjectMapper().readValue(new File("testfile"), CustomClass.class);

then fromFile.descriptions.get("desc2") is of type LinkedHashMap instead of type CustomClass.NameVal.

How can I get Jackson to properly parse the type of the CustomClass.NameVal descriptors (other than making some class that wraps the parsing and explicitly converts the LinkedHashMap after Jackson reads the file)?

Try this. Create a class Description with name and value attributes:

public class Description {
    private String name;
    private double val;
}

Now in your CustomClass do this:

public class CustomClass {
     List<Description> descriptions;
}

And that's it. Remember to create getters and setters because Jackson needs it.

You could try something like this:

public class DescriptionWrapper {
    private Description descriptions;

    public Description getDescriptions() {
        return descriptions;
    }

    public void setDescriptions(Description descriptions) {
        this.descriptions = descriptions;
    }
}

public class Description {
    private String desc1;
    private NameValue desc2;

    public String getDesc1() {
        return desc1;
    }

    public void setDesc1(String desc1) {
        this.desc1 = desc1;
    }

    public NameValue getDesc2() {
        return desc2;
    }

    public void setDesc2(NameValue desc2) {
        this.desc2 = desc2;
    }
}

public class NameValue {
    private String name;
    private double val;

    public String getName() {
         return name;
    }

    public void setName(String name) {
         this.name = name;
    }

    public double getVal() {
         return val;
    }

    public void setVal(double val) {
         this.val = val;
    }
}    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM