This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 4 years ago.
How do I parse a JSON feed in Android?
Android has all the tools you need to parse json built-in. Example follows, no need for GSON or anything like that.
Get your JSON:
Assume you have a json string
String result = "{\"someKey\":\"someValue\"}";
Create a JSONObject:
JSONObject jObject = new JSONObject(result);
If your json string is an array, e.g.:
String result = "[{\"someKey\":\"someValue\"}]"
then you should use JSONArray as demonstrated below and not JSONObject
To get a specific string
String aJsonString = jObject.getString("STRINGNAME");
To get a specific boolean
boolean aJsonBoolean = jObject.getBoolean("BOOLEANNAME");
To get a specific integer
int aJsonInteger = jObject.getInt("INTEGERNAME");
To get a specific long
long aJsonLong = jObject.getLong("LONGNAME");
To get a specific double
double aJsonDouble = jObject.getDouble("DOUBLENAME");
To get a specific JSONArray:
JSONArray jArray = jObject.getJSONArray("ARRAYNAME");
To get the items from the array
for (int i=0; i < jArray.length(); i++)
{
try {
JSONObject oneObject = jArray.getJSONObject(i);
// Pulling items from the array
String oneObjectsItem = oneObject.getString("STRINGNAMEinTHEarray");
String oneObjectsItem2 = oneObject.getString("anotherSTRINGNAMEINtheARRAY");
} catch (JSONException e) {
// Oops
}
}
Writing JSON Parser Class
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;
}
}
Parsing JSON Data
Once you created parser class next thing is to know how to use that class. Below i am explaining how to parse the json (taken in this example) using the parser class.
2.1. Store all these node names in variables: In the contacts json we have items like name, email, address, gender and phone numbers. So first thing is to store all these node names in variables. Open your main activity class and declare store all node names in static variables.
// url to make request
private static String url = "http://api.9android.net/contacts";
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
// contacts JSONArray
JSONArray contacts = null;
2.2. Use parser class to get JSONObject and looping through each json item. Below i am creating an instance of JSONParser class and using for loop i am looping through each json item and finally storing each json data in variable.
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
contacts = json.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone number is agin JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
}
} catch (JSONException e) {
e.printStackTrace();
}
I've coded up a simple example for you and annotated the source. The example shows how to grab live json and parse into a JSONObject for detail extraction:
try{
// Create a new HTTP Client
DefaultHttpClient defaultClient = new DefaultHttpClient();
// Setup the get request
HttpGet httpGetRequest = new HttpGet("http://example.json");
// Execute the request in the client
HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
// Grab the response
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
// Instantiate a JSON object from the request response
JSONObject jsonObject = new JSONObject(json);
} catch(Exception e){
// In your production code handle any errors and catch the individual exceptions
e.printStackTrace();
}
Once you have your JSONObject refer to the SDK for details on how to extract the data you require.
Related
This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 4 years ago.
How do I parse a JSON feed in Android?
Android has all the tools you need to parse json built-in. Example follows, no need for GSON or anything like that.
Get your JSON:
Assume you have a json string
String result = "{\"someKey\":\"someValue\"}";
Create a JSONObject:
JSONObject jObject = new JSONObject(result);
If your json string is an array, e.g.:
String result = "[{\"someKey\":\"someValue\"}]"
then you should use JSONArray as demonstrated below and not JSONObject
To get a specific string
String aJsonString = jObject.getString("STRINGNAME");
To get a specific boolean
boolean aJsonBoolean = jObject.getBoolean("BOOLEANNAME");
To get a specific integer
int aJsonInteger = jObject.getInt("INTEGERNAME");
To get a specific long
long aJsonLong = jObject.getLong("LONGNAME");
To get a specific double
double aJsonDouble = jObject.getDouble("DOUBLENAME");
To get a specific JSONArray:
JSONArray jArray = jObject.getJSONArray("ARRAYNAME");
To get the items from the array
for (int i=0; i < jArray.length(); i++)
{
try {
JSONObject oneObject = jArray.getJSONObject(i);
// Pulling items from the array
String oneObjectsItem = oneObject.getString("STRINGNAMEinTHEarray");
String oneObjectsItem2 = oneObject.getString("anotherSTRINGNAMEINtheARRAY");
} catch (JSONException e) {
// Oops
}
}
Writing JSON Parser Class
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;
}
}
Parsing JSON Data
Once you created parser class next thing is to know how to use that class. Below i am explaining how to parse the json (taken in this example) using the parser class.
2.1. Store all these node names in variables: In the contacts json we have items like name, email, address, gender and phone numbers. So first thing is to store all these node names in variables. Open your main activity class and declare store all node names in static variables.
// url to make request
private static String url = "http://api.9android.net/contacts";
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
// contacts JSONArray
JSONArray contacts = null;
2.2. Use parser class to get JSONObject and looping through each json item. Below i am creating an instance of JSONParser class and using for loop i am looping through each json item and finally storing each json data in variable.
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
contacts = json.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone number is agin JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
}
} catch (JSONException e) {
e.printStackTrace();
}
I've coded up a simple example for you and annotated the source. The example shows how to grab live json and parse into a JSONObject for detail extraction:
try{
// Create a new HTTP Client
DefaultHttpClient defaultClient = new DefaultHttpClient();
// Setup the get request
HttpGet httpGetRequest = new HttpGet("http://example.json");
// Execute the request in the client
HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
// Grab the response
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
// Instantiate a JSON object from the request response
JSONObject jsonObject = new JSONObject(json);
} catch(Exception e){
// In your production code handle any errors and catch the individual exceptions
e.printStackTrace();
}
Once you have your JSONObject refer to the SDK for details on how to extract the data you require.
This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 4 years ago.
How do I parse a JSON feed in Android?
Android has all the tools you need to parse json built-in. Example follows, no need for GSON or anything like that.
Get your JSON:
Assume you have a json string
String result = "{\"someKey\":\"someValue\"}";
Create a JSONObject:
JSONObject jObject = new JSONObject(result);
If your json string is an array, e.g.:
String result = "[{\"someKey\":\"someValue\"}]"
then you should use JSONArray as demonstrated below and not JSONObject
To get a specific string
String aJsonString = jObject.getString("STRINGNAME");
To get a specific boolean
boolean aJsonBoolean = jObject.getBoolean("BOOLEANNAME");
To get a specific integer
int aJsonInteger = jObject.getInt("INTEGERNAME");
To get a specific long
long aJsonLong = jObject.getLong("LONGNAME");
To get a specific double
double aJsonDouble = jObject.getDouble("DOUBLENAME");
To get a specific JSONArray:
JSONArray jArray = jObject.getJSONArray("ARRAYNAME");
To get the items from the array
for (int i=0; i < jArray.length(); i++)
{
try {
JSONObject oneObject = jArray.getJSONObject(i);
// Pulling items from the array
String oneObjectsItem = oneObject.getString("STRINGNAMEinTHEarray");
String oneObjectsItem2 = oneObject.getString("anotherSTRINGNAMEINtheARRAY");
} catch (JSONException e) {
// Oops
}
}
Writing JSON Parser Class
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;
}
}
Parsing JSON Data
Once you created parser class next thing is to know how to use that class. Below i am explaining how to parse the json (taken in this example) using the parser class.
2.1. Store all these node names in variables: In the contacts json we have items like name, email, address, gender and phone numbers. So first thing is to store all these node names in variables. Open your main activity class and declare store all node names in static variables.
// url to make request
private static String url = "http://api.9android.net/contacts";
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
// contacts JSONArray
JSONArray contacts = null;
2.2. Use parser class to get JSONObject and looping through each json item. Below i am creating an instance of JSONParser class and using for loop i am looping through each json item and finally storing each json data in variable.
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
contacts = json.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone number is agin JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
}
} catch (JSONException e) {
e.printStackTrace();
}
I've coded up a simple example for you and annotated the source. The example shows how to grab live json and parse into a JSONObject for detail extraction:
try{
// Create a new HTTP Client
DefaultHttpClient defaultClient = new DefaultHttpClient();
// Setup the get request
HttpGet httpGetRequest = new HttpGet("http://example.json");
// Execute the request in the client
HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
// Grab the response
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
// Instantiate a JSON object from the request response
JSONObject jsonObject = new JSONObject(json);
} catch(Exception e){
// In your production code handle any errors and catch the individual exceptions
e.printStackTrace();
}
Once you have your JSONObject refer to the SDK for details on how to extract the data you require.
This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 4 years ago.
How do I parse a JSON feed in Android?
Android has all the tools you need to parse json built-in. Example follows, no need for GSON or anything like that.
Get your JSON:
Assume you have a json string
String result = "{\"someKey\":\"someValue\"}";
Create a JSONObject:
JSONObject jObject = new JSONObject(result);
If your json string is an array, e.g.:
String result = "[{\"someKey\":\"someValue\"}]"
then you should use JSONArray as demonstrated below and not JSONObject
To get a specific string
String aJsonString = jObject.getString("STRINGNAME");
To get a specific boolean
boolean aJsonBoolean = jObject.getBoolean("BOOLEANNAME");
To get a specific integer
int aJsonInteger = jObject.getInt("INTEGERNAME");
To get a specific long
long aJsonLong = jObject.getLong("LONGNAME");
To get a specific double
double aJsonDouble = jObject.getDouble("DOUBLENAME");
To get a specific JSONArray:
JSONArray jArray = jObject.getJSONArray("ARRAYNAME");
To get the items from the array
for (int i=0; i < jArray.length(); i++)
{
try {
JSONObject oneObject = jArray.getJSONObject(i);
// Pulling items from the array
String oneObjectsItem = oneObject.getString("STRINGNAMEinTHEarray");
String oneObjectsItem2 = oneObject.getString("anotherSTRINGNAMEINtheARRAY");
} catch (JSONException e) {
// Oops
}
}
Writing JSON Parser Class
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;
}
}
Parsing JSON Data
Once you created parser class next thing is to know how to use that class. Below i am explaining how to parse the json (taken in this example) using the parser class.
2.1. Store all these node names in variables: In the contacts json we have items like name, email, address, gender and phone numbers. So first thing is to store all these node names in variables. Open your main activity class and declare store all node names in static variables.
// url to make request
private static String url = "http://api.9android.net/contacts";
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
// contacts JSONArray
JSONArray contacts = null;
2.2. Use parser class to get JSONObject and looping through each json item. Below i am creating an instance of JSONParser class and using for loop i am looping through each json item and finally storing each json data in variable.
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
contacts = json.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone number is agin JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
}
} catch (JSONException e) {
e.printStackTrace();
}
I've coded up a simple example for you and annotated the source. The example shows how to grab live json and parse into a JSONObject for detail extraction:
try{
// Create a new HTTP Client
DefaultHttpClient defaultClient = new DefaultHttpClient();
// Setup the get request
HttpGet httpGetRequest = new HttpGet("http://example.json");
// Execute the request in the client
HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
// Grab the response
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
// Instantiate a JSON object from the request response
JSONObject jsonObject = new JSONObject(json);
} catch(Exception e){
// In your production code handle any errors and catch the individual exceptions
e.printStackTrace();
}
Once you have your JSONObject refer to the SDK for details on how to extract the data you require.
I am developing android app where I am getting web-service data as:
"[{\"ID\":51,\"Text\":\"!! SAMPLE PROJECT !!\"},{\"ID\":58,\"Text\":\"01 Contracting Test Project\"},{\"ID\":64,\"Text\":\"1212\"},{\"ID\":45,\"Text\":\"CHEMICAL FACTORY PROJECT\"}]"
Now I want to parse this data in json I used replaceAll() function to replace backslashes from the string like this:
String jsonFormattedString = line.replaceAll("\\\\", "");
But I think this method isnot good to work with because it removes all the backslashes from the string which creates problems like I recieved json node like:
"[{\"ID\":9617,\"Text\":\"1 1\/4\\\" PVC\/GI CLAMPS\"}]"
where the string value for Text contains double quotes within string which creates problem for me. So my question is what is the best way to parse this json data in java.
My full json data returned by webservice is as:
"[{\"ID\":51,\"Text\":\"!! SAMPLE PROJECT !!\"},{\"ID\":58,\"Text\":\"01 Contracting Test Project\"},{\"ID\":64,\"Text\":\"1212\"},{\"ID\":45,\"Text\":\"CHEMICAL FACTORY PROJECT\"},{\"ID\":53,\"Text\":\"Kanix City\"},{\"ID\":54,\"Text\":\"KANIX DREAM CITY\"},{\"ID\":59,\"Text\":\"KANIX DREAM CITY -- PHASE II\"},{\"ID\":62,\"Text\":\"KANIX DREAM CITY PHASE I\"},{\"ID\":55,\"Text\":\"Kishor_TEST\"},{\"ID\":63,\"Text\":\"Next Generation Housing\"},{\"ID\":65,\"Text\":\"Nothing Job\"},{\"ID\":56,\"Text\":\"PAVAN_TEST\"},{\"ID\":46,\"Text\":\"PRODUCTION UNITS\"},{\"ID\":1,\"Text\":\"PROJECT-01(TYPE 1)\"},{\"ID\":3,\"Text\":\"PROJECT-02(TYPE 1)\"},{\"ID\":5,\"Text\":\"PROJECT-03(TYPE 1)\"},{\"ID\":6,\"Text\":\"PROJECT-04(TYPE 1)\"},{\"ID\":7,\"Text\":\"PROJECT-05(TYPE 1)\"},{\"ID\":8,\"Text\":\"PROJECT-06(TYPE 1)\"},{\"ID\":2,\"Text\":\"PROJECT-07(TYPE 2)\"},{\"ID\":4,\"Text\":\"PROJECT-08(TYPE 2)\"},{\"ID\":9,\"Text\":\"PROJECT-09(TYPE 3)\"},{\"ID\":10,\"Text\":\"PROJECT-10(TYPE 3)\"},{\"ID\":11,\"Text\":\"PROJECT-11(TYPE 4)\"},{\"ID\":57,\"Text\":\"Reviera Classic\"},{\"ID\":43,\"Text\":\"ROAD PROJECT\"},{\"ID\":41,\"Text\":\"SAMPLE PROJECT 1\"},{\"ID\":42,\"Text\":\"SAMPLE PROJECT 2\"},{\"ID\":52,\"Text\":\"Shailesh Test project#1000\"},{\"ID\":61,\"Text\":\"VISHAL PARADISE\"},{\"ID\":60,\"Text\":\"WTC\"}]"
my full code is like this:
#Override
protected List<CItem> doInBackground(String... params) {
try {
String line="";
String ur = "http://"+ServerDetails.hostServer+"/appservices.svc/Projects?Keyword=" ;
lstItm=new ArrayList<CItem>() ;
// Replace it with your own WCF service path
URL json = new URL(ur);
URLConnection jc = json.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(jc.getInputStream()));
line = reader.readLine();
Log.d("LINE",line);
JSONArray array=new JSONArray(line);
Itm=new CItem( "-1", "Select Project" );
lstItm.add(Itm);
for(int i=0; i < array.length(); i++) {
JSONObject tmpJson=array.getJSONObject(i);
Itm=new CItem(tmpJson.getString("ID"),tmpJson.getString("Text"));
lstItm.add(Itm);
}
return lstItm ;
}
catch(Exception e)
{
Log.d("ERRROR--->",e.getMessage());
}
return lstItm ;
}
#mubu9082 ..you dont need to remove these backslashes...
as this json string is shown with backslashes in log or by debugger..
just parse it as usual
public void jsonParser()
{
ArrayList<> list=new ArrayList<>(); //declare this as global
String responseString="[{\"ID\":51,\"Text\":\"!! SAMPLE PROJECT !!\"},{\"ID\":58,\"Text\":\"01 Contracting Test Project\"},{\"ID\":64,\"Text\":\"1212\"},{\"ID\":45,\"Text\":\"CHEMICAL FACTORY PROJECT\"}]";
JSONArray array=new JSONArray(responseString);
String id[]=new String[array.length()];
String text[]=new String[array.length()];
for(int i=0;i<array.length();i++)
{
JSONObject tmpJson=array.getJSONObject(i);
id[i]=tmpJson.getString("ID");
text[i]=tmpJson.getString("TEXT");
CItem Itm=new CItem(tmpJson.getString("ID"),tmpJson.getString("Text")); lstItm.add(Itm);
list.add(Itm);
}
}
do this to get response from server
try {
// create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// make GET request to the given URL ...use
HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
// receive response as inputStream
HttpEntity entity = httpResponse.getEntity();
String response= EntityUtils.toString(entity);
//pass this response to JSONArray object
//save response and then flush the entity.
entity.consumeContent();
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
pass this response to JSONArray object
public InsuranceDO getInsuranceData1(Context context) {
String urlStr = "http://192.168.2.11:8080/Service/category/sample";
InsuranceDO insuranceDO = new InsuranceDO();
HttpURLConnection urlConnection;
List<InsuranceDO> insList = new ArrayList<InsuranceDO>();
try {
String reqVal = "T=421D84EAC8DEB4878CE48C8A0CB870791EB96FE51C7800A8806032A8CE69A4966D87FFA2E139EE6586C1924F9BD070154CB7E8F92985AC6674B0AD37D9F3FC1ED7B2E4C2D01E5525DCE5E6FCDA26AF890633011894AA2B72604CC8B046E4F9C37DE9A61EECD7000325D3EC673E8609AAD753C52B9BC002C014BC18A35AA8AB3636C237088A08EEED72A7C5F2EDE60155E9111A6F74F082C0E4B45D484C00CA5AD5B3560B8A10D47616E48077EBDE490E&UserCode=172278&DBSource=bali";
URL url = new URL(urlStr);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
OutputStream outputStream = urlConnection.getOutputStream();
outputStream.write(reqVal.getBytes());
outputStream.flush();
int code = urlConnection.getResponseCode();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
StringBuilder result = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
/**
* To parse json to list data
*/
JSONArray jsonArray = new JSONArray(result.toString());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
insuranceDO.setAgeing(jsonObject.getString("xxx"));
insuranceDO.setInsuredName(jsonObject.getString("yyyy"));
insuranceDO.setProposalNumber(jsonObject.getString("zzzz"));
insuranceDO.setReason(jsonObject.getString("aaaa"));
insList.add(insuranceDO);
}
} catch (Exception e) {
Toast.makeText(context, e.toString(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
Toast.makeText(context, insList.toString(), Toast.LENGTH_LONG).show();
return insuranceDO;
}
I want to fetch json data from this link: link
& here is my code for that:
private static String url = "https://graph.facebook.com/fql?q=SELECT%20url,%20normalized_url,%20share_count,%20like_count,%20comment_count,%20total_count,%20commentsbox_count,%20comments_fbid,%20click_count%20FROM%20link_stat%20WHERE%20url=%27https://www.facebook.com/BillionHands%27";
// JSON Node names
private static final String TAG_DATA = "data";
private static final String TAG_SHARE = "share_count";
private static final String TAG_LIKE = "like_count";
private TextView LikeTv;
public String like;
JSONArray data = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about_us);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
data = json.getJSONArray(TAG_DATA);
JSONObject c = data.getJSONObject(0);
// Storing each json item in variable
String share = c.getString(TAG_SHARE);
like = c.getString(TAG_LIKE);
Log.i("Like Count",like);
} catch (JSONException e) {
e.printStackTrace();
}
LikeTv = (TextView) findViewById(R.id.tvLike);
LikeTv.setText(like);
Now I am getting "JSONException: no value for data" Please help... whats wrong in my code..
Well....
I got your problem solution...
The method you wrote getJSONFromUrl()..
I am sure it contains HttpPost object..
change that to HttpGet and it will start working...
EDIT
Here is the code I tried with
public class MainActivity extends Activity {
private static String url = "https://graph.facebook.com/fql?q=SELECT%20url,%20normalized_url,%20share_count,%20like_count,%20comment_count,%20total_count,%20commentsbox_count,%20comments_fbid,%20click_count%20FROM%20link_stat%20WHERE%20url=%27https://www.facebook.com/BillionHands%27";
// JSON Node names
private static final String TAG_DATA = "data";
private static final String TAG_SHARE = "share_count";
private static final String TAG_LIKE = "like_count";
private TextView LikeTv;
public String like;
JSONArray data = null;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONfromURL(url);
try {
// Getting Array of Contacts
Log.d("JSON ","DATA "+json);
data = json.getJSONArray(TAG_DATA);
JSONObject c = data.getJSONObject(0);
// Storing each json item in variable
String share = c.getString(TAG_SHARE);
like = c.getString(TAG_LIKE);
Log.i("Like Count",like);
} 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.activity_main, menu);
return true;
}
}
class JSONParser
{
public JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
// http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// convert response to string
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();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag get data string ",
"Error converting result " + e.toString());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag create object ",
"Error parsing data " + e.toString());
}
return jArray;
}
}
The "data" element in your JSON isn't an array, it is a JSONobject. So instead of:
JSONArray data = json.getJSONArray(TAG_DATA);
Try this:
JSONObject data = json.getJSONObject(TAG_DATA);
From the JSONObject, you can get items like TAG_SHARE and TAG_LIKE.
Good luck!