I have a Json to parse, but the structure is unknown. Is their a way to determine the number and field names? I want to parse it and store as Array of HashMap. I have the following the code, but it works only if I know the name of the fields within an individual row.
import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.ArrayList;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public ArrayList<LinkedHashMap<String,String>> JsonFileToJsonRows()
{
JSONParser parser = new JSONParser();
ArrayList<LinkedHashMap<String ,String>> Json_rows = new ArrayList<LinkedHashMap<String,String>>() ;
try
{
JSONArray jsonarray = (JSONArray) parser.parse(new FileReader("filename"));
for (Object row : jsonarray)
{
JSONObject rowjson = (JSONObject) row;
String field1 = (String) rowjson.get("field1");
String field2 = (String) rowjson.get("field2");
LinkedHashMap <String, String> extend_row =new LinkedHashMap <String, String>();
extend_row.put("field1",field1);
extend_row.put("field2", field2);
Json_rows.add(extend_row);
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (ParseException e)
{
e.printStackTrace();
}
return Json_rows;
}
}
How can I find the fieldnames for field1 and field2.
My Json structure is an array of json objects.
[ {"field1": "field1data1","field2": "field2data1"},
{"field1": "field1data2","field2": "field2data2" }]