Search code examples
javajacksonpojo

Java Jackson - how to parse list of objects with an arbatrary identifier tag


I have a JSON record that looks like this:

    {"ActionRecord": {
        "101": {
            "Desc": "string 1",
            "Done": 1,
            "MaxTimes": 2,
            "Point": 30,
            "Times": 4
        },
        "102": {
            "Desc": "string 2",
            "Done": 1,
            "MaxTimes": 3,
            "Point": 15,
            "Times": 13
        },
        "103": {
            "Desc": "string 3.",
            "Done": 1,
            "MaxTimes": 5,
            "Point": 15,
            "Times": 24
        }, ... }

I can get Jackson to parse this if i create a hacky intermediate class that contains a field for each number, and then use something like this in the class:

    @JsonProperty( value = "101" )
    public MyClass hundred_one;
    @JsonProperty( value = "102" )
    public MyClass hundred_two;
    @JsonProperty( value = "103" )
    public MyClass hundred_three;

But I have to type out all the expected values, so it would be much easier to be able to use an array list of objects, and insert the numeric id into the POJO with Jackson's mapper.

Is there a way have Jackson automatically map it into a class like this? :

public enum ActionRecord { 

Something   ( "101" ),
SomethingElse( "102" ),
AnotherSomething ( "103" ),
;    
String _id;    
EK_DailyTaskInfo_ActionRecord( String id )
{
   _id = id;
}    
public String getId()
{
   return _id;
}        
public String  Desc;     // "some string.",
public boolean Done;     // 1,
public int     Times;    // 4
public int     MaxTimes; // 2,
public int     Point;    // 30,
}

It does not have to be an enum this was just something I was trying before I gave up


Solution

  • Jackson can decode it into a Map<String, Record> for you, e.g.

    public class Record {
    public String  Desc;     // "some string.",
    public boolean Done;     // 1,
    public int     Times;    // 4
    public int     MaxTimes; // 2,
    public int     Point;    // 30,
    }
    
    public class ActionRecords {
    public Map<String, Record> ActionRecord
    }