从Json数据中排除属性而不对其进行反序列化

时间:2015-08-28 06:56:48

标签: java json jackson

我有这样的Json数据:

{
"_id": "123",
"transaction": {
    "className": "ExpenseReport",
    "id": "789",
    "createdBy": {
        "firstName": "Donald",
        "lastName": "Morgan",
        "address": {
            "street1": "1362 Woodlawn Lane",
            "street2": "Suite #100805",
            "place": {
                "city": "Darien",
                "state": "CA",
                "country": "USA",
                "number": "OBJ-4823478",
                "createdBy": "Brett Wright"
            },
            "zip": 88884,
            "number": "OBJ-5740231",
            "createdBy": "Brett Wright"
        },
        "number": "OBJ-3561551",
        "createdBy": "Brett Wright"
    },
    "score": 12,
    "reasonCodes": [
        "these",
        "are",
        "strings"
    ]
}
}

在排除某些属性之后我想要这个数据的子集,比如说:

{
"_id": "123",
"transactionType": "EXPENSE_REPORT",
"transaction": {
    "className": "ExpenseReport",
    "id": "789",
    "createdBy": {
        "firstName": "Donald",
        "lastName": "Morgan",
        "address": {
            "street1": "1362 Woodlawn Lane",
            "street2": "Suite #100805",
            "place": {
                "city": "Darien",
                "state": "CA",
                "country": "USA"
            },
            "createdBy": "Brett Wright"
        },
        "createdBy": "Brett Wright"
    },
    "score": 12
}
}

现在一种方法是将原始json数据反序列化到POJO中,使用Jackson Views注释所需的属性,然后再次序列化相同的POJO以获取Json数据而不用属性。

但是我想要实现类似没有DESERIALIZING Json数据的东西,比如解析json数据并删除键集值(如果在集合中找不到它们)。是否有人知道有任何图书馆这样做?

1 个答案:

答案 0 :(得分:2)

Jackson允许您仅使用ObjectMapper.readTree()

执行解析步骤
JsonNode root = om.readTree(input);

结果JsonNode是可变的,所以这样的工作就可以了:

ObjectNode place = (ObjectNode)(root.findPath("transaction")
    .findPath("createdBy")
    .findPath("address")
    .findPath("place")
);
place.remove("number");

这是 - 不幸的是 - 不太好,但可以很容易地包装到一个采用属性路径的通用方法中:

void deleteProperty(JsonNode root, List<String> propPath)
{
   JsonNode node = root;

   for (String propName: propPath.subList(0, propPath.size() - 1)) {
       node = node.findPath(propName);
   }
   // completely ignore missing properties
   if ((! node.isMissingNode()) && (! node.isEmpty())) {
       if (node instanceof ObjectNode) {
           final ObjectNode parent = (ObjectNode)node;
           parent.remove(propPath.get(propPath.size() - 1));
       }
   }
}

然后可以使用writeTree()写出修改后的节点树。

还有property filter API。不幸的是,虽然使用它过滤掉单个属性很容易,但属性路径为non-trivial to use it。例如,在您的情况下,普通过滤器只能过滤掉所有 createdBy属性。