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

520 Views Asked by At

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
1

There are 1 best solutions below

0
On BEST ANSWER

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");
    ......
}