0

What is the best way to iterate through a comma delimited json node called 'name' in the scenario below?

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);
}
dbc
  • 104,963
  • 20
  • 228
  • 340
ermalsh
  • 191
  • 1
  • 16

1 Answers1

1

Yes, if you want to split the single node into essentially two, String.split would be the obvious solution.

It would probably be nicest if your target class had a Builder you can create it with, so you can do something like this:

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;
}
daniu
  • 14,137
  • 4
  • 32
  • 53