将参数传递给自定义反序列化器

时间:2015-02-05 22:42:54

标签: java json mapping jackson deserialization

我的json包含多行。

{
    "rows": [{
        "aId": 408,
        "aFrstNm": "TIM",
    },
    {
        "aId": 410,
        "aFrstNm": "BOB",
    },
    {
        "aId": 409,
        "aFrstNm": "HENRY",
    }]
}

和POJOs

public class User extends Employee {
    @JsonProperty("tableName")
    private Double aID;
    @JsonProperty("aFrstNm")
    private String aFrstNm;

    getters and setters ommitted
}

public class Employee {
}


public class Employees {
   private Collection<? extends Employee> rows;

   getters and setters ommitted
}

我想要做的是将User类传递给自定义反序列化器,以便能够将员工作为扩展Employee的用户集合返回:

    SimpleModule simpleModule = new SimpleModule("MyModule")
        .addDeserializer(Employees.class, new JsonDeserializer<Employees>() {
            @Override
            public Employees deserialize(JsonParser p, DeserializationContext  ctxt) throws IOException {
                ObjectMapper mapper = (ObjectMapper) p.getCodec();
                final Class<?> clazz = (Class<?>) ctxt.getAttribute("mappingClass");
                final JsonNode jsonNode = (JsonNode) mapper.readTree(p).get("rows");
                Employees employees = new Employees();
                Collection<Product> rows = new ArrayList();
                if (jsonNode.isArray()) for (final JsonNode objNode : jsonNode) {
                    boolean isValueNode = objNode.isValueNode();
                    String json = mapper.writeValueAsString(objNode);
                    Product product = (Product) new ObjectMapper().readValue(json, clazz);
                    rows.add(product);
                    System.out.println(jsonNode);
                }
                employees.setRows(rows);
               return employees;
            }
        });
    mapper.registerModule(simpleModule);

变量clazz(final Class clazz)属性应该包含类a参数。到目前为止,我一直无法找到允许这种情况的机制。 DeserializationContext似乎很有希望,但我无法做到这一点。有关使用DeserializationContext或其他方式传递参数的任何建议吗?

TNX。

0 个答案:

没有答案