Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to populate data to a Json Template

I have a Json Format as a Template (Temp.json). Below is the format of my Template

{
  "products":[
    {
      "ProductTitleName": "",
      "ImageUrl":""
    }
  ]
}

Now I have to Populate Data to this format, basically products array will have many object Nodes. I have used JsonPath expressions to extract relevant attribute value from Raw Json.My Problem is how can I use this Template and Populate data to this structure.

Reason to use Template Json -

  1. I used a Template json to avoid pojo classes
  2. Though JsonPath expressions helps to extract necessary attributes and set them to target attribute final Json out put result I build previously is on-the-fly (Runtime).
  3. If suppose I'm going to add another attribute along with those attributes later, it would be easier and to good avoid code changes.

so to avoid those mentioned reasons, I planned to have a Template json and adhere to that structure, is this a good approach, if so help me out to populate data to the template, if not help me out with a better approach.

like image 815
Keshan Nageswaran Avatar asked Aug 25 '16 11:08

Keshan Nageswaran


1 Answers

If you need only to avoid pojo classes you can use a generic Map to do the same. In this case you don't need to parse the basic template.

Map<String, Object> products = new HashMap<>();
List<Map<String, Object>> listProducts = new ArrayList<>();

for () { // Loop over products
    Map<String, Object> product = new HashMap<>();
    product.put("ProductTitleName", "YourTitle");
    product.put("ImageUrl", "YourImageUrl");
    listProducts.add(product);
}

products.put("products", listProducts);
// Now you can use products Map instead of an equivalent pojo class

If you need to use a template try to use Velocity. It is a template engine that works well to build text file (in this case a json file), but from a template. It is not limited to files, it works also with strings or streams if necessary.

like image 60
Davide Lorenzo MARINO Avatar answered Oct 21 '22 11:10

Davide Lorenzo MARINO