0

Assignment: I am using json-simple. How can I convert this json data into individual java strings? (Please forgive me if you think that this is a low-level question - I am new to JSON, so I don't know much about that - I've searched a lot, but I couldn't find any answers)


I can get the data if there is only one object ... like this ...

{
    "name": "Abhi",
    "age": "21"
}

But, I can't get the data if it is in the array

[{
    "name": "Abhi",
    "age": "21"
}, {
    "name": "shek",
    "age": "7"
}]

my program logic for json object

    JSONParser parser = new JSONParser();

    Object obj = parser.parse(new FileReader("A:/c/dataFile.json"));

    JSONObject jObj = (JSONObject) obj;

    String gName = (String) jObj.get("name");
    String gAge = (String) jObj.get("age");
    System.out.println(gName);
    System.out.println(gAge);

Can anyone show me how to get the data? maybe a code snippet?

Thanks in advance for your answer!

abhishake
  • 763
  • 9
  • 16
  • 1
    When processing a JSON array you shouldn't cast your `Object` to `JSONObject` but rather to `JSONArray`, which you will iterate over to retrieve the `JSONObject`s it contains. – Aaron Oct 28 '16 at 09:52
  • If you need to test whether you received an array or an object, check [`JSONStructure`](http://docs.oracle.com/javaee/7/api/javax/json/JsonStructure.html) and its `getValueType` method. – Aaron Oct 28 '16 at 09:53
  • On which base I can separate both of the objects? – abhishake Oct 28 '16 at 10:25
  • `JSONArray` extends `List`, you can iterate it as any `List` in order to handle each of its elements individually. – Aaron Oct 28 '16 at 10:37

1 Answers1

0

Because in your second case you are getting JSONArray you may need to check the instance of obj as

if (jObj instanceof JSONObject)

else if (jObj instanceof JSONArray)
mhasan
  • 3,703
  • 1
  • 18
  • 37