无法使用POJO类将Map反序列化为值

时间:2014-03-13 01:12:21

标签: java json jackson

我正在尝试将以下JSON结构解析为自定义java对象模型,如下所示。

当我运行测试时出现错误:

  

org.codehaus.jackson.map.JsonMappingException:无法识别的字段   “arbitraryKey1”(Class DemoClass),未标记为可忽略

如何在MiddleClass中注释“离开”地图

{
    "fieldA": {
        "arbitraryKey1" : { 
            "innerFieldA": "foo",
            "innerFieldB": "bar"
        },
        "arbitraryKey2" : { 
            "innerFieldA": "testing",
            "innerFieldB": "123"
        }
    },
    "fieldB": {
        "arbitraryKeyX" : { 
            "innerFieldA": "more",
            "innerFieldB": "testing"
        }
    }
}

以下是我的java类:

public class DemoClass {
    @JsonProperty
    public MiddleClass fieldA;

    @JsonProperty
    public MiddleClass fieldB;
}

public class MiddleClass {
    public Map<String, LeafClass> leaves;

    public LeafClass getLeaf( String name ) { return leaves.get(name); }
}

public class LeafClass {
    public String innerFieldA;
    public String innerFieldB;
}

public class DemoTest {
    @Test
    public void testReadValue() {
        DemoClass demo = ObjectMapper().readValue( json, DemoClass.class );
        assertEquals( demo.fieldA.leaves.get("arbitraryKey1").innerFieldA, "foo" );
        assertEquals( demo.fieldB.getLeaf("arbitraryKeyX").innerFieldB, "testing" );
    }
}

1 个答案:

答案 0 :(得分:0)

您的MiddelClass应如下所示:

class MiddleClass {

    public Map<String, LeafClass> leaves = new HashMap<String, LeafClass>();

    @JsonAnyGetter
    public LeafClass getLeaf(String name) {
        return leaves.get(name);
    }

    @JsonAnySetter
    public void addLeaf(String key, LeafClass value) {
        leaves.put(key, value);
    }

    @Override
    public String toString() {
        return leaves.toString();
    }
}

@JsonAnySetter注释可以解决问题。