Java中的逗号吐出/定界jsonnode

时间:2019-06-01 05:33:59

标签: java iterator delimiter comma jsonnode

在以下情况下,通过逗号分隔的json节点(称为“ name”)进行迭代的最佳方法是什么?

        GetStoredValue result = 
        dataManagerService.getStoredValue(itemId).checkedGet();
        JsonNode node = mapper.readTree(result.getStoredString());
        if (node.has("name")
            && node.has("price")
            && node.has("sku"))
        {
            //iterate through comma delimited "name" value and return the dataSources
            //node: {"name":"test1,test2", "price":30, "sku":"123123123"}

            //return:
            //{"name":"test1", "price":30, "sku":"123123123"}
            //{"name":"test2", "price":30, "sku":"123123123"}

            ComboPooledDataSource dataSource = createDataSource(node);
            dataSources.put(itemId, dataSource);
            return dataSources.get(itemId);
        }

1 个答案:

答案 0 :(得分:1)

是的,如果您想将单个节点实质上分为两个,String.split将是显而易见的解决方案。

如果您的目标类有一个可以用来创建它的生成器,那可能是最好的,所以您可以执行以下操作:

private List<Product> fromJsonNode(JsonNode node) {
    String[] names = node.get("name").textValue().split(",");
    // create list of known size
    List<Product> products = new ArrayList<>(ids.length);
    // these values will remain the same for all products
    ProductBuilder builder = Product.builder()
                                    .price(node.get("price").numberValue())
                                    .sku(node.get("sku").textValue());
    for (String name : names) {
        // just set the name and create the product with it
        products.add(builder.name(name).build());
    }
    return products;
}