0

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" }]

AMisra
  • 1,869
  • 2
  • 25
  • 45
  • 2
    JSONObject extends HashMap. – user253751 Feb 19 '15 at 19:06
  • Possible duplicate of [java iterate over JSONObject?](http://stackoverflow.com/questions/9151619/java-iterate-over-jsonobject) – CaptJak Feb 25 '16 at 19:23
  • This should show you how to iterate over a JSONObject to get the fields/keys: http://stackoverflow.com/questions/9151619/java-iterate-over-jsonobject – gus27 Feb 19 '15 at 19:30

0 Answers0