Search code examples
javasimplejson

fill array from json file without knowing the keys


I have the following Json file and I want to create list of array ,i don't know the keys name (like person ,lastname etc ) it can be many entities like employes users etc but the structure of the file must be exactly the same ,how can i do that ?

the file is

{
    "Person": [
        {
            "name": "Peter",
            "lastname": "ta",
            "age": 43,
            "sex": "male"
        },
        {
            "name": "Zara",
            "lastname": "treg",
            "age": 25,
            "sex": "female"
        }
    ]
}

what I need is to create list of array like this

person ,name,peter ,lastname,ta,age,43,sex,male
person ,name,zara ,lastname,treg,age,23,sex,female

....

I started with the following code to get the file but since i dont know the name of the keys I dont know how to proceed.

JSONObject jsonObject= (JSONObject) parser.parse(new FileReader("C:\\General\\jsonperson.txt"));

Solution

  • Check Example 4 on this page: https://code.google.com/p/json-simple/wiki/DecodingExamples

    Specifically, this part:

    Map json = (Map)parser.parse(jsonText, containerFactory);
    Iterator iter = json.entrySet().iterator();
    System.out.println("==iterate result==");
    while(iter.hasNext()){
      Map.Entry entry = (Map.Entry)iter.next();
      System.out.println(entry.getKey() + "=>" + entry.getValue());
    }
    
    System.out.println("==toJSONString()==");
    System.out.println(JSONValue.toJSONString(json));
    

    That's how you might iterate over the entries of a JSONObject. By the way, with this library, if it's the one I think you're using, a JSONObject is just a java.util.Map, and you can use all of its methods - that's why it works for this example to cast the parse result to a Map.

    All of the JSON <-> Java object mappings for this lib: https://code.google.com/p/json-simple/wiki/MappingBetweenJSONAndJavaEntities