javajsonhive-query

Accessing the column names from the string containing a JSON in java


I have a string in java

String val = "{"column":[{"name":"id,"type":"int"},{"name":"empname","type":"string"}], "database":"test","table":"sample"}"

How do I retrieve only the column name My result must be a string containing the column names delimited by tabspace i.e

Expected Output

id      empname

Solution

  • Your JSON is not valid (it seems that "is missing after id among other issues), but assuming you'd have a similarly structured valid one, you could use lib org.json as stated in accepted answer of this question: How to parse JSON in Java ?

    In your case, you need following code:

    import org.json.*;
    
    JSONObject obj = new JSONObject(val); 
    JSONArray arr = obj.getJSONArray("column");
    for (int i = 0; i < arr.length(); i++)
    {
        String post_id = arr.getJSONObject(i).getString("name");
        ......
    }