skip to Main Content

I am trying to PARSE Json and pull values based on input key. JSON structure is not same every time
below is sample JSON structure and JSON starts and ends with [] and some time {}

[
    {
        "id": "0001",
        "type": "donut",
        "name": "Cake",
        "ppu": 0.55,
        "days": {
            "weekdays": "Friday",
            "weekends": "Sunday",
        },
        "batters": {
            "batter": [
                {
                    "id": "1001",
                    "type": "Regular"
                },
                {
                    "id": "1002",
                    "type": "Chocolate"
                },
            ]
        },
        "topping": [
            {
                "id": "5001",
                "type": "None"
            },
            {
                "id": "5002",
                "type": "Glazed"
            },
        ]
    }
]
{
        "id": "0001",
        "type": "donut",
        "name": "Cake",
        "ppu": 0.55,
        "days": {
            "weekdays": "Friday",
            "weekends": "Sunday",
        },
        "batters": {
            "batter": [
                {
                    "id": "1001",
                    "type": "Regular"
                },
                {
                    "id": "1002",
                    "type": "Chocolate"
                },
            ]
        },
        "topping": [
            {
                "id": "5001",
                "type": "None"
            },
            {
                "id": "5002",
                "type": "Glazed"
            },
        ]
    }

i tried below code

import org.json.simple.*;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

    public static void main(String[] args) throws IOException, Exception {

        File InputFolder = new File(System.getProperty("user.dir") + "//Files//new.json");

        JsonElementFromFile(InputFolder,"name");        
    }

public static void JsonElementFromFile(File FilePath, String key) throws IOException, Exception {
  
   JSONParser parser = new JSONParser();
   FileReader reader = new FileReader(FilePath);
   JSONArray obj = (JSONArray) parser.parse(reader);  
   for (Object o : obj) { 
      JSONObject json = (JSONObject) o; 
      String jsonKeyValue = (String)json.get(key).toString(); 
      System.out.println(key + " : " + jsonKeyValue); }
  
  }
  1. above code works when JSON data start with "[" but not working if it start with "{" , irrespective of any structure I should be able to get value
  2. i am able to pull only value from first object keys "id","type","name","ppu" but when i pass key as "days.weekdays" it is not pulling. even if i have more arrays and objectsi should be able to pull just by passing path of key, ex: "batters.batter[0].id" or "batters.batter[1].type"**
  3. basically i am looking for reusable code to pull values based on keys passed, dont want to hardcode any values from JSON.

thank you

2

Answers


  1. Chosen as BEST ANSWER

    i found easy way for this question. using com.fasterxml.jackson , we can pull any any value from JSON ,

    enter code here
     filepath= place where file stored
     nodepath= path of node 
        File File = new File(filePath);
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonTree = objectMapper.readTree(File);
        String value = jsonTree.at(nodepath).asText();
        return value;
    

  2. If you don’t want to hardcode for different JSON structure, the solution is to use JSON query library.

    https://github.com/octomix/josson

    Deserialize Array

    Josson array = Josson.fromJsonString(
        "[" +
        "    {" +
        "        "id": "0001"," +
        "        "type": "donut"," +
        "        "name": "Cake"," +
        "        "ppu": 0.55," +
        "        "days": {" +
        "            "weekdays": "Friday"," +
        "            "weekends": "Sunday"" +
        "        }," +
        "        "batters": {" +
        "            "batter": [" +
        "                {" +
        "                    "id": "1001"," +
        "                    "type": "Regular"" +
        "                }," +
        "                {" +
        "                    "id": "1002"," +
        "                    "type": "Chocolate"" +
        "                }" +
        "            ]" +
        "        }," +
        "        "topping": [" +
        "            {" +
        "                "id": "5001"," +
        "                "type": "None"" +
        "            }," +
        "            {" +
        "                "id": "5002"," +
        "                "type": "Glazed"" +
        "            }" +
        "        ]" +
        "    }," +
        "    {" +
        "        "batters": {" +
        "            "batter": [" +
        "                {" +
        "                    "id": "1003"," +
        "                    "type": "Special"" +
        "                }," +
        "                {" +
        "                    "id": "1004"," +
        "                    "type": "DarkChocolate"" +
        "                }" +
        "            ]" +
        "        }" +
        "    }" +
        "]");
    

    Deserialize Object

    Josson object = Josson.fromJsonString(
        "{" +
        "    "id": "0001"," +
        "    "type": "donut"," +
        "    "name": "Cake"," +
        "    "ppu": 0.55," +
        "    "days": {" +
        "        "weekdays": "Friday"," +
        "        "weekends": "Sunday"" +
        "    }," +
        "    "batters": {" +
        "        "batter": [" +
        "            {" +
        "                "id": "1001"," +
        "                "type": "Regular"" +
        "            }," +
        "            {" +
        "                "id": "1002"," +
        "                "type": "Chocolate"" +
        "            }" +
        "        ]" +
        "    }," +
        "    "topping": [" +
        "        {" +
        "            "id": "5001"," +
        "            "type": "None"" +
        "        }," +
        "        {" +
        "            "id": "5002"," +
        "            "type": "Glazed"" +
        "        }" +
        "    ]" +
        "}");
    

    Query

    System.out.println(array.getString("batters.batter[0].id"));       // 1001
    System.out.println(object.getString("batters.batter[0].id"));      // 1001
    System.out.println(array.getString("batters.batter[1].type"));     // Chocolate
    System.out.println(object.getString("batters.batter[1].type"));    // Chocolate
    System.out.println(array.getString("[0].batters.batter[1].id"));   // 1002
    System.out.println(array.getString("[1].batters.batter[1].type")); // DarkChocolate
    System.out.println(array.getString("batters.batter[3].type"));     // DarkChocolate
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search