Am new to android. Am creating an android project which parses the JSON data and displays it in a ListView. Am using Eclipse to create the project. I have created a file called userinput.json in the raw folder which is subfolder of res. I have given these JSON data inside the file.
[
{"name":"Company A", "hometown":"NJ"},
{"name":"Company B", "hometown":"PA"},
{"name":"Company C", "hometown":"CT"},
{"name":"Company D", "hometown":"NY"},
{"name":"Company E", "hometown":"NJ"}
]
My requirement is to convert this JSON data declared in the Raw resources into JSON array. Since I have declared the json data in a file, I have to access it from the resources and hence I use BufferedReader to read the file. But while trying to convert the StringBuilder object to JSON array, I am returned with null. This is the code I have written:
BufferedReader jsonReader = new BufferedReader(new InputStreamReader(
this.getResources().openRawResource(R.raw.userinput)));
StringBuilder jsonBuilder = new StringBuilder();
try {
for (String line = null; (line = jsonReader.readLine()) != null;)
{
jsonBuilder.append(line).append("\n");
}
jTokener = new JSONTokener(jsonBuilder.toString());
jsonArray = new JSONArray(jTokener.toString());
}
catch (Exception e)
{
throw new RuntimeException(e);
}
ArrayList<User> newArrayOfUsers = User.JsonData(jsonArray);
In a seperate Java file I have the below two methods to convert my JSON Array into Java Objects:
public User(JSONObject object)
{
try
{
this.name = object.getString(name);
this.hometown = object.getString(hometown);
}
catch(JSONException e)
{
e.printStackTrace();
}
}
public static ArrayList<User> JsonData(JSONArray jsonArray)
{
ArrayList<User> users = new ArrayList<User>();
for(int i = 0; i < jsonArray.length(); i++)
{
try
{
users.add(new User(jsonArray.getJSONObject(i)));
}
catch(JSONException e)
{
e.printStackTrace();
}
}
return users;
}
I am not sure, whether am doing this in correct way, Can anyone please guide me how to get JSON array from the StringBuilder?