Reputation: 24472
I got the following JSON data from my API:
Json array and alot of json objects in it.
How do I get a json array without a name?
This is what I tried:
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
result = j.getJSONArray('');
for(int i=0;i<j.length();i++){
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
Log.d("tag", "NAME IS: " +json.getString("name"));
}
}
the json
variable stores all the json data!
Upvotes: 0
Views: 3503
Reputation: 82
create JSONParser class which contains json parsing code.
Mention in Your MainActivity.java
JSONParser jsonparser=new JSONParser(); JSONObject jsonObject=jsonparser.getJSONFromURL(URL);
Now Create separate JSONParser class
class JSONParser
{
public static JSONObject jsonObject=null;
public static String json=null;
InputStream is=null;
public JSONObject getJSONFromURL(String url)
{
try
{
HttpClient client=new DefaultHttpClient();
HttpPost post=new HttpPost(url);
HttpResponse response=client.execute(post);
HttpEntity entity=response.getEntity();
is=entity.getContent();
}
catch(Exception e)
{
e.printStackTrace();
}
try
{
BufferedReader br=new BufferedReader(new InputStreamReader(is,"UTF-8"));
StringBuilder sb=-new StringBuilder();
String line=null;
while((br.readLine())!=null)
{
sb.append(line+"\n");
}
json=sb.toString();
is.close();
}
catch(Exception e)
{
e.printStackTrace();
}
try
{
jsonObject=new JSONObject(json.subString(json.indexOf("{"),json.lastinddexOf("}")+1));
}
catch(Exception e)
{
e.printStackTrace();
}
return jsonObject;
}
Now in MainActivity.java
try
{
JSONParser jsonparser=new JSONParser();
JSONObject jsonObject=jsonparser.getJSONFromURL(URL);// URL is a String which contains url
Log.d("Response:",jsonObject.toString());
JSONArray jsonarray=new JSONArray(jsonObject.getString("YourFirstJSONArrayName"));//YourJSONArray contains the response array
for(int i=0;i<jsonarray.length();i++)
{
JSONObject c=jsonarray.getJSONObject(i);
// now get data from c object
}
// Now getting data from Second Array
JSONArray jsona=new JSONArray(jsonObject.getString("YourSecondJSONArrayName"));
for(int j=0;j<jsona.length();j++)
{
JSONObject c=jsona.getJSONObject(j);
// now get data from json data from second array
}
}
catch(Exception e)
{
e.printStackTrace();
}
Upvotes: -1
Reputation: 5741
JSONArray has a constructor which takes a String source.
JSONArray array = new JSONArray(yourJSONArrayAsString);
Then you can get each object using for loop.
JSONArray array;
try {
array = new JSONArray(yourJSONArrayAsString);
for(int i=0;i<array.length();i++){
JSONObject obj = array.getJSONObject(i);
// get your data from jsonobject
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Upvotes: 3