Extracting Values Not Working JSON file? - java

I am newbie in java programming. I am trying to get Instagram users full name. and below is my code
package gibs.smith.testapp;
import android.os.AsyncTask;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class fetchData extends AsyncTask<Void,Void,Void> {
private String name = "";
private String link ="";
#Override
protected Void doInBackground(Void... voids) {
try {
URL url= new URL("https://instagram.com/priya.p.varrier/?__a=1");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while (line !=null){
line =bufferedReader.readLine();
JSONObject jo= new JSONObject(line);
JSONObject user=jo.getJSONObject("user");
name=user.getString("full_name");
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
MainActivity.data.setText(this.name);
}
}
but it is not working. it dose not extracts the string value "full_name".
It is retrieving the JSON file but not the desired value.
The URL is https://instagram.com/priya.p.varrier/?__a=1
any help would be great.
----Edit-----
adding graphql object causes app crash and below is catlog output
here is the log
https://justpaste.it/1itsa

First the bug. It must be NullPointerException.
while (line !=null)
it will run until line = null. Then this line will give you the exception.
new JSONObject(line);
and you shoud get the graphql first.
so the solution should look like this.
if(line != null) {
JSONObject jo = new JSONObject(line);
JSONObject graphql = jo.getJSONObject("graphql");
JSONObject user = graphql.getJSONObject("user");
name = user.getString("full_name");
}

As per your JSON
your full_name key is inside user JSONObject which is inside graphql JSONObject.
So to get the full_name value you have to first retrieve graphql JSONObject.
JSONObject jo = new JSONObject(line);
JSONObject graphqlObj = jo.getJSONObject("graphql");
JSONObject user = jographqlObj.getJSONObject("user");
name=user.getString("full_name");
You can use http://jsonviewer.stack.hu/ to check JSON structure of your file.

Related

My android studio app keeps crashing after using a background method to read a json from my fragment

I am making an app using the Kitsu API. Here in this moment I have a fragment that allows me to search different anime using the api to get information such as name, synopsis, etc. After parsing the information I proceed to go back to my main activity to pass it to my new fragment, but it crashes the moment I initialize the method to go back to my main activity. My question is how do I use a fragment to read a JSON with a background class using ASYNCTASK and display it in a new fragment?
I have noticed that it jumps around a lot from my fragment, in an activity different from my main, to a class running in the background, to my main, to my fragment. Below are images of my code. Thank you very much.
Search fragment code, Main Activity search related methods, Search results background tasks, Search Results Fragment. To clarify It stops before I get to the string I labeled crashpoint and doesn't make it to the search results fragment. I felt like it would be handy to have that bit of code in there. Here is the error I get with my code when I run it.
You don't need to create a new fragment after reading JSON. Just to post an simple code that read JSON with async task:
package com.example.compsci_734t;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.ArrayList;
import java.util.zip.GZIPInputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ListActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class People extends Activity{
ArrayList<String> items = new ArrayList<String>();
static InputStream is = null;
//private static String url = "";
//private static String url = "http:...";
private static String url = "http....";
//URL requestUrl = new URL(url);
JSONArray people = null;
private static final String TAG_COURSES = "Courses";
static JSONObject jObj = null;
static String json = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.people);
new MyTasks().execute();
}
private class MyTasks extends AsyncTask<URL, Void, JSONObject> {
#Override
protected JSONObject doInBackground(URL... urls) {
// return loadJSON(url);
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
//HttpPost httpPost = new HttpPost(url);
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
/*BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 8);*/
InputStream inputStream = is;
GZIPInputStream input = new GZIPInputStream(inputStream);
InputStreamReader reader = new InputStreamReader(input);
BufferedReader in = new BufferedReader(reader);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = in.readLine()) != null) {
sb.append(line);
//System.out.println(line);
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
JSONArray people = new JSONArray(json);
//JSONArray people = new JSONArray(json);
for (int i = 0; i < people.length(); i++) {
//System.out.println(courses.getJSONObject(i).toString());
JSONObject p = people.getJSONObject(i);
// Storing each json item in variable
String person_id = p.getString("someString1");
items.add(person_id);
/*Log.v("--", "People: \n" + "\n UPI: " + person_id);*/
}
//jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
protected void onPostExecute(JSONObject json) {
ListView myListView = (ListView)findViewById(R.id.peopleList);
myListView.setAdapter(new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_1, items));
}
}
The sample code was taken from this answer.

Parsing extremely simple JSON from a URL in in Android

I have tried everything online to try to parse this JSON but nothing seems to work. Here is the JSON:
{"salonphoebe":true,"salonvo":false}
That's it. It is only booleans. It is from an HTTP website if that is important at all.
How do I do parse this extremely simple JSON from http://example.com in Java in Android Studio? I am trying to create Booleans based on these in my app. I know this question is on this website a lot but I have literally tried 10 solutions but nothing will work. Thank you.
Try the following code.
try {
JSONObject json = new JSONObject(your - json - string - here);
boolean b1 = json.optBoolean("salonphoebe");
boolean b2 = json.optBoolean("salonvo");
} catch (JSONException e) {
e.printStackTrace();
}
Okay I have solved my own problem. Here is everything I learned and what I did. I want to help anyone else with this problem if they come across this issue. First I added this to my androidmanifest.xml:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Then I added this between the tags in the androidmanifest.xml beucase the link I am parsing the JSON from is an HTTP link:
android:usesCleartextTraffic="true"
Really quickly import all of this into your mainactiviy.java:
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
Then we get into the hard stuff. There are two parts to parsing JSON data from the internet. First, you must read the JSON (meaning put the JSON from online into a String) from the URL and then you must organize the String of JSON into separate variables. So let's start on the HTTP Request. I created an Async class in my MainActivity.java (under the OnCreate) that I found online that looks like this:
public class HttpGetRequest extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
try {
String url = "http://example.com/example.php";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
System.out.println("Test");
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
String jsonResponse = response.toString();
return jsonResponse;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject json = new JSONObject(result);
boolean myJsonBool = json.optBoolean("samplestringinyourjson");
if(hasPaid){
//do something
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Okay so basically the reason we put this in an Async class is because java won't let you make an HTTP Request in your OnCreate. What the doInBackground is doing is fetching the JSON data and putting it into the string like I said. The OnPostExecute is separating that string into boolean values and doing stuff with it. Lastly, paste this into your OnCreate or it won't work:
new HttpGetRequest().execute();
That's it. If you have questions ask and hopefully I can see it.

Using Java with SleepyMongoose to perform MongoDB inserts

this is my first post here.
In a nutshell, I've set up a MongoDB instance, and installed a REST service to run commands on it. The one I chose was SleepyMongoose.
I've been trying to write a simple Java program to do three things: a find, an insert, and another find. Basically, display the collection, insert something, and display it again to show the update. The finds work correctly, but the insert has been giving me trouble.
The documentation of SleepyMongoose uses curl with a data parameter, but I've been using Java's HttpURLConnection. How can I add that data parameter to the HttpURLConnection? Here's what I've been trying:
private static void POST (String command) {
try {
// The 'command' is just going to be 'insert' for now.
URL restURL = new URL(REST + DATABASE + "/" + COLLECTION + "/_" + command);
HttpURLConnection conn = (HttpURLConnection) restURL.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.connect();
OutputStream out = conn.getOutputStream();
String x = "docs=[{'x':1}]";
out.write(x.getBytes());
out.close();
conn.disconnect();
}
catch (Exception e) {
System.out.println("Uh oh...");
e.printStackTrace();
}
}
Am I even using SleepyMongoose for its correct purpose? Are there better alternatives? I'm not tied down to any REST api, but I'd like to get the inserts down.
Thanks everyone
For some reason, it only works if there's a reader attached to it, too. If I attach the following immediately after the write, it works perfectly:
String line, output = "";
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = rd.readLine()) != null)
output += line;
rd.close();
Can someone explain this?
I happen to be writing similar code for an Android project and have had success with the below when doing a POST.
Note that the data you get back will need to be parsed as it comes in as a HttpResponse. I have been converting it to a String then pulling out JSON values (see below).
Sample insert:
String[] link2 = {"http://XXX.XXX.XXX.XXX:27080/foo/bar/_insert", "[{\"x\":2},{\"x\":3}]"};
new HTTPPost().execute(link2);
Code for POST, yours will be different due to not writing for Android specifically. Replace AndroidHttpClient with HttpClient. Note the BasicNameValuePair used to specify "docs" as key.
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
protected HttpResponse doInBackground(String... params) {
String link = params[0];
String value = params[1];
HttpPost post = new HttpPost(link);
AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("docs", value));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
return client.execute(post);
} catch (IOException e) {
return null;
} finally {
client.close();
}
}
To parse to string:
String test = EntityUtils.toString(result.getEntity());
To pull out JSON values:
public String parseJSON(String toParse)
{
try {
JSONObject jObject = new JSONObject(toParse);
String aJsonString = jObject.getString("ok");
JSONArray jArray = jObject.getJSONArray("results");
for (int i = 0; i < jArray.length(); i++) {
try {
JSONObject oneObject = jArray.getJSONObject(i);
// Pulling items from the array
String oneObjectsItem = oneObject.getString("link");
return oneObjectsItem;
} catch (JSONException e) {
// Oops
}
}
} catch (Exception ex) {
}
return "";
}

Json parse from URL

I am getting java.lang.NullPointerException when I run this. Does anyone know why this is happening and how I can fix it?
Please take a look at my code and let me know if you have any suggestions.
{"begin":[{"id":1,"name":"Andy","size":1}],"open":[{"id":1,"name":"Tom","size":2}]}
Fragment
public class MainFragment extends Fragment {
public MainFragment() {}
//URL to get JSON Array
private String url = "URL...";
//JSON Node Names
private static final String TAG_BEGIN = "begin";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_SIZE = "size";
JSONArray begin = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
new JSONParse().execute();
return rootView;
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(HomeActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array
begin = json.getJSONArray(TAG_BEGIN);
JSONObject c = begin.getJSONObject(0);
// Storing JSON item in a Variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String size = c.getString(TAG_SIZE);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
JSONParser
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Error:
E/JSON Parserīš• Error parsing data org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
FATAL EXCEPTION: main
java.lang.NullPointerException
at
...$MainFragment$JSONParse.onPostExecute(MainActivity.java:399)
at
...$MainFragment$JSONParse.onPostExecute(MainActivity.java:373)
Which is...
begin = json.getJSONArray(TAG_BEGIN);
and...
private class JSONParse extends AsyncTask<String, String, JSONObject> {
EDIT (Answer)
JSONParser
Inside of JSONParser I changed my code to this:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpUriRequest request = new HttpGet(url);
request.setHeader("Accept", "application/json");
HttpResponse response = httpClient.execute(request);
HttpEntity httpEntity = response.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Inside of onPostExecute
JSONArray begin = json.getJSONArray(TAG_BEGIN);
for (int i = 0; i < begin(); i++) {
try {
JSONObject b = = begin(i);
String id = b.getString(TAG_ID);
String name = b.getString(TAG_NAME);
String size = b.getString(TAG_SIZE);
} catch (JSONException e) {
e.printStackTrace();
}
}
First make sure your JSONObject is not null. Then slowly transverse line by line based off the type.
JSONArray begin = json.getJSONArray(TAG_BEGIN);
Then possibly do something like this?
for(int n = 0; n < begin.length(); n++)
{
JSONObject object = begin.getJSONObject(n);
// query through the array
String id = object.getString(TAG_ID);
String name = object.getString(TAG_NAME);
String size = object.getString(TAG_SIZE);
//Now do something with the strings
}
Of course you'd do the same thing with the TAG_OPEN. Let me know if this works, I'll gladly help as much as possible.
the error shows that the return string of you http request is not only the json data
something like <!DOCTYPE are includeed
please check you are request the right url, and the server handle the request correctly
you can use your browser visit the url you request and check the return result
I am not using a fragment but here is similar solution.
Change your url and key values for retrieving values from json. I didn't have your url so i used some other. Please check it out. Same concept except i am not using fragments but this json parsing code works just fine.
First of all, you have to deal with the network on main thread exception
Add:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
in your class,
and
ADD this to ManiFestFile:
<uses-permission android:name="android.permission.INTERNET"/>
MainActivity.Java
package com.example.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.Menu;
public class MainActivity extends Activity {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Making HTTP request
String url = "http://api.androidhive.info/contacts/";
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting JSON Array
JSONArray begin = json.getJSONArray("contacts");
JSONObject c = begin.getJSONObject(0);
// Storing JSON item in a Variable
String id = c.getString("id");
String name = c.getString("name");
String size = c.getString("email");
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
JSONParser.Java
package com.example.test;
import android.os.StrictMode;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}

JSON reads me only objects, no arrays

I'm using Eclipse, for an application where I have to read a JSON file from an URL.
The code I'm using is this one:
http://collegewires.com/android/2012/06/json-parsing-in-android/
Ok, the CLASS which I'm using for reading JSON files is called Parser.java:
package com.cw.json;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
public class Parser {
static InputStream is = null;
static JSONObject jsonObject = null;
static String json = "";
// class constructor
public Parser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException exception) {
exception.printStackTrace();
} catch (ClientProtocolException exception) {
exception.printStackTrace();
} catch (IOException exception) {
exception.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sBuilder.append(line + "\n");
}
is.close();
json = sBuilder.toString();
} catch (Exception exception) {
exception.printStackTrace();
}
// Parsing the string to a JSON object
try {
jsonObject = new JSONObject(json);
} catch (JSONException exception) {
exception.printStackTrace();
}
// JSON String
return jsonObject;
}
}
I was using this code for reading a JSON file which is directly an ARRAY, but the code gives me an error.
My question is: is it possible to read an Array instead always reading an Object??
maybe using another class?
Try to modify your Parser.java to this, so you gat a Array not a Object. And please buy you a JAVA Book for beginners, so you do learn how to speak JAVA
public JSONArray getJSONFromUrl(String url) {
....
static JSONArray jsonArray = null;
....
// Parsing the string to a JSON Array
try {
jsonArray = new JSONArray(json);
} catch (JSONException exception) {
exception.printStackTrace();
}
return jsonArray;
}

Categories

Resources