0

I have a Java function that loads JSON from a URL and then returns it as a JSONObject

The function I am using is: json = new JSONObject(jsonString); from org.json.JSONObject

The problem is that any arrays being contained in the object are just returned as strings, not as arrays.

We also don't know the format of the JSON being included so we can't specifically call a property of the object to parse. It just has to be able to handle any arrays that might exist.

How can I fix this?

marcusds
  • 784
  • 1
  • 7
  • 26

2 Answers2

0

You can use Gson for parsing json string. Its clean and easy.

For using Gson, you need to create a class first describing a single response object like this.

public class ResponseObject {
    public String id;
    public String name;
} 

Now as you already have the json string containing an array of objects, parse the json string as follows.

Gson gson = new Gson();
ResponseObject[] objectArray = gson.fromJson(jsonString, ResponseObject[].class); 

Simple!

Reaz Murshed
  • 23,691
  • 13
  • 78
  • 98
  • Same as Jan Kaufmann's answer, problem with this is that it means the Java has to know the format of the JSON, but it does not. Java returns the JSONObject to a Velocity template, so the Java needs to be able to handle arrays in the object without knowing the format. – marcusds Dec 15 '16 at 22:04
0

If you still want the JSONObject, the way you retrieve the array is actually..

JSONObject jsonObject = new JSONObject(jsonString);
JSONArray hobbies = jsonObject.getJSONArray("hobbies");

So that

hobbies.getString(0)
hobbies.getString(1)
etc..

JSONArray itself has .get(), getDouble(), getInt(), etc..

Fevly Pallar
  • 3,059
  • 2
  • 15
  • 19
  • Problem with this is that it means the Java has to know the format of the JSON, but it does not. Java returns the JSONObject to a Velocity template, so the Java needs to be able to handle arrays in the object without knowing the format. – marcusds Dec 15 '16 at 22:02
  • Shouldn't it be your own responsibility to do so? yet you were not asking about iteration of the format nor giving the structure of json. It's then the same as *do it/my work for me*, to check whether or not the entry is array its discussed many times in SO, like this [one](http://stackoverflow.com/questions/9988287/test-if-it-is-jsonobject-or-jsonarray) – Fevly Pallar Dec 16 '16 at 09:49