parse Json in Android app - java

I need help in parsing big Json file:
{"status":{"code":200,"text":"OK"},"content":[{"proposalId":"12536","providerId":"1","supervisorName":null,"supervisorEmail":"lolbroek_13#hotmail.com","hostInstitution":"qsd","hostCountry":"qsd","hostCity":"QSD","hostTypeId":"1","title":"qsd","status":"available","numberStudents":null,"description":"qsd","categoryId":"34","startDate":null,"endDate":null,"submitDate":null,"expectedWorkload":null,"purpose":null,"workOrganisationId":"1","function":null,"audienceId":"1","preConditions":"","certificationGranted":null,"deliverables":null,"expenses":null,"revenue":null,"vacancies":null,"uploadImg":"http:\/\/193.136.60.238\/\/MUTW2012\/core\/img\/internship.png"},
{"proposalId":"12537","providerId":"1","supervisorName":null,"supervisorEmail":"lolbroek_13#hotmail.com","hostInstitution":"qsd","hostCountry":"qsd","hostCity":"QSD","hostTypeId":"1","title":"qsd","status":"available","numberStudents":null,"description":"qsd","categoryId":"34","startDate":null,"endDate":null,"submitDate":null,"expectedWorkload":null,"purpose":null,"workOrganisationId":"1","function":null,"audienceId":"1","preConditions":"","certificationGranted":null,"deliverables":null,"expenses":null,"revenue":null,"vacancies":null,"uploadImg":"http:\/\/193.136.60.238\/\/MUTW2012\/core\/img\/internship.png"},
{"proposalId":"12538","providerId":"1","supervisorName":null,"supervisorEmail":"lolbroek_13#hotmail.com","hostInstitution":"qsd","hostCountry":"qsd","hostCity":"QSD","hostTypeId":"1","title":"qsd","status":"available","numberStudents":null,"description":"qsd","categoryId":"34","startDate":null,"endDate":null,"submitDate":null,"expectedWorkload":null,"purpose":null,"workOrganisationId":"1","function":null,"audienceId":"1","preConditions":"","certificationGranted":null,"deliverables":null,"expenses":null,"revenue":null,"vacancies":null,"uploadImg":"http:\/\/193.136.60.238\/\/MUTW2012\/core\/img\/internship.png"},
{"proposalId":"12539","providerId":"1","supervisorName":null,"supervisorEmail":"lolbroek_13#hotmail.com","hostInstitution":"qsd","hostCountry":"qsd","hostCity":"QSD","hostTypeId":"1","title":"qsd","status":"available","numberStudents":null,"description":"qsd","categoryId":"34","startDate":null,"endDate":null,"submitDate":null,"expectedWorkload":null,"purpose":null,"workOrganisationId":"1","function":null,"audienceId":"1","preConditions":"","certificationGranted":null,"deliverables":null,"expenses":null,"revenue":null,"vacancies":null,"uploadImg":"http:\/\/193.136.60.238\/\/MUTW2012\/core\/img\/internship.png"},
................[etc]
I need to take all titles and proposalIds in content.
I tried to make it like this:
public ArrayList<String> GetUserProposals(String UserId){
String actionname = sitename+"accounts/"+UserId+"/proposals";
try {
jObject = this.sendData(actionname);//change later
// return result;
JSONArray ja = jObject.getJSONArray("content");
for (int i = 0; i < ja.length(); i++) {
Log.i("MyDebug", "value----" + ja.getJSONObject(i).getString("title"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ArrayList<String> returnValue = null;
return returnValue;
}
But JSONArray is empty.

My JSON String was
{
"result": "success",
"countryCodeList": [
{
"countryName": "World Wide",
"countryCode": "00"
},
{
"countryName": "Korea, Republic of",
"countryCode": "kr"
},
{
"countryName": "United States",
"countryCode": "us"
},
{
"countryName": "Japan",
"countryCode": "jp"
},
{
"countryName": "China",
"countryCode": "cn"
},
{
"countryName": "India",
"countryCode": "in"
}
]
}
And I parsed this way
JSONObject json = new JSONObject(jsonstring);
status = json.getString("result");
if (status.equalsIgnoreCase("success")) {
JSONArray nameArray = json.names();
JSONArray valArray = json.toJSONArray(nameArray);
JSONArray valArray1 = valArray.getJSONArray(1);
valArray1.toString().replace("[", "");
valArray1.toString().replace("]", "");
int len = valArray1.length();
for (int i = 0; i < valArray1.length(); i++) {
Country country = new Country();
JSONObject arr = valArray1.getJSONObject(i);
country.setCountryCode(arr.getString("countryCode"));
country.setCountryName(arr.getString("countryName"));
arrCountries.add(country);
}
}

you should try switching your jObject = this.sendData(actionname); to 'jObject = new JSONObject(this.sendData(actionname));`
you have to initialize the JSON object and you aren't...

This will help you Dude..while Parsing JSON there will be json array [] and json object {}
DefaultHttpClient httpclient = new DefaultHttpClient(
new BasicHttpParams());
HttpPost httppost = new HttpPost(
"Your Json URL");
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
HttpResponse response = null;
try {
response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
BufferedReader reader = null;
reader = new BufferedReader(new InputStreamReader(inputStream,
"UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
result = sb.toString();
int k = 0;
JSONObject jObject = null;
jObject = new JSONObject(result);
String aJsonString = jObject.getString("results");
String name = aJsonString;
JSONArray jArray = null;
jArray = jObject.getJSONArray("results");
JSONObject oneObject = null;
oneObject = jArray.getJSONObject(0);
JSONArray jArray1 = null;
jArray1 = oneObject.getJSONArray("address_components");//keyword
JSONObject oneObject1 = null;
oneObject1 = jArray1.getJSONObject(1);
String oneObjectsItem1 = oneObject1.getString("long_name");//keyword
City = oneObjectsItem1;
}
catch (IOException e) {
int x = 0;
}
return City;

Related

How to get the string of a json child in a json array

I will like to get the value of a JSON string in a JSON file the string is nested in a JSON array I am using android studio here is my JSON file
{
"Amber":
{
"Info": {
"name": "Amber",
"bio": "Turkish-Cypriot",
"image": "null"
},
"Class": {
"Adorable": {
"name": "",
"link": ""
},
"IronAge": {
"name": "",
"link": ""
}
}
}
}
I will like to get the value of name and bio to a string here is the java code i have tried
#SuppressLint("StaticFieldLeak")
public class AsyncHttpTask_GetWebData extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpsURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpsURLConnection) url.openConnection();
if (result != null) {
String response = streamToString(urlConnection.getInputStream());
parseResult_GetWebData(response);
return result;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
if (result != null) {
Toast.makeText(MainActivity.this, "Data Loaded Successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Failed to Data!", Toast.LENGTH_SHORT).show();
}
}
}
private String streamToString(InputStream stream) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
String line;
String result = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
if (null != stream) {
stream.close();
}
return result;
}
private void parseResult_GetWebData(String result) {
try {
JSONObject response = new JSONObject(result);
JSONArray jsonArray = response.getJSONArray("Amber");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject =jsonArray.optJSONObject(i);
JSONObject jsonObject1 = jsonObject.getJSONObject("Info");
String name = jsonObject1.optString("name");
textView.setText(name);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
The textview is empty and not showing the result but i am getting the OnPostExecute toast saying the Data is loaded successfully but the value is not displaying in the textview
firstly, I suggest you use the Gson library to convert the Json.
Secondly, the JsonArray is for the following format:
"arrary_key": [
{
"name": "Jeff Bridges",
"id": "162655890",
"characters": [
"Jack Prescott"
]
},
{
"name": "Charles Grodin",
"id": "162662571",
}
]
so the second it is still a JsonObject
JSONObject response = new JSONObject(result);
JSONObject jsonObject = response. getJSONObject("Amber");
or you can ask the service to return jsonArray

type java.lang.String cannot be converted to JSONObject at org.json.JSON.typeMismatch(JSON.java:111)

Could you help ?
My PHP web service read send this JSON:
{
"version": "1",
"id": "1",
"title": "John",
"text": "Joe",
"language": "French",
"image": "ic_launcher1",
"audio": "au_sound1",
}
My Android Rest client code return this following error :
{
"version": "1",
"id": "1",
"title": "John",
"text": "Joe",
"language": "French",
"image": "ic_launcher1",
"audio": "au_sound1",
}
of type java.lang.String cannot be converted to JSONObject at org.json.JSON.typeMismatch(JSON.java:111)
Android client code is below :
private void webServiceClient (String serviceUrl) {
String jsonContent;
InputStream inputStream = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(serviceUrl);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
}
catch (Exception e) {
Log.e("Webservice 1", e.toString());
}
try {
// read the json file ----------------------------------------
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"), 8000);
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
reader.close();
jsonContent = sb.toString();
if (jsonContent != null) {
JSONObject jsonObject = new JSONObject(jsonContent);
if (jsonObject != null) {
JSONArray sectionArray = null;
String language = jsonObject.get("language").toString();
switch (language) {
case "French":
sectionArray = (JSONArray) jsonObject.get("section_fr");
break;
case "English":
sectionArray = (JSONArray) jsonObject.get("section_en");
break;
case "Arabic":
sectionArray = (JSONArray) jsonObject.get("section_ar");
break;
default:
break;
}
List<String> sections = new ArrayList<String>();
for (int i = 0; i < sectionArray.length(); i++) {
String oneSection = sectionArray.get(i).toString();
sections.add(oneSection);
Log.d(TAG, "section %%%%%%%%%%%%%%%%%%%%%%%%%%%%%"
+ oneSection);
}
/*
* jsonObject.get("id"); jsonObject.get("title");
* jsonObject.get("text"); jsonObject.get("language");
*/
addSections(jsonObject.get("id").toString(), jsonObject
.get("language").toString(), sections);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
The JSON is seems to have something wrong I don't knowYour help bill be very appreciated.
the json is not valid. You have an extra comma in the end
"audio": "au_sound1",
}
should be
"audio": "au_sound1"
}
also chage
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
with
jsonContent = EntityUtils.toString(entity)

how to code json array without array name?

I'm new to JSON android java eclipse. I am doing a listview with images and parsing json array. I followed this tutorial: http://www.wingnity.com/blog/android-json-parsing-and-image-loading-tutorial/ . In that tutorial, their JSON array contains the array name.However, mine doesn't contain the array name. So my question is how to code JSON Array without the array name?
Below is my JSON code.
[
{ "event_id": "EV00000001",
"event_title": "Movie 1",
},
{
"event_id": "EV00000002",
"event_title": "Movie2",
}
]
Below is my JSON coding for parsing the JSON.
protected Boolean doInBackground(String... urls) {
try {
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("actors");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Events event = new Events();
event.setevent_title(object.getString("event_title"));
eventList.add(event);
}
return true;
}
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
What am i suppose to do?
This problem is solved. Thus, i will be posting the correct code.
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONArray array = new JSONArray(data);
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
Events event = new Events();
event.setevent_title(obj.getString("event_title"));
eventList.add(event);
}
return true;
}
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
Here is a little example:
JSONArray array = new JSONArray();
JSONObject obj1 = new JSONObject();
obj1.put("key", "value");
array.put(obj1);
JSONObject obj2 = new JSONObject();
obj2.put("key2", "value2");
array.put(obj2);
That would look like:
[
{
"key": "value"
},
{
"key2": "value2"
}
]
If you want to get information about your JSONObjects in your JSONArray just iterate over them:
for (int i = 0; i < array.length(); i++) {
JSONObject object = (JSONObject) array.get(i);
object.get("event_id");
object.get("event_title");
}
You can use GSON librery, it's very easy to use. Just create a class (model)
public class Event{
private String event_id;
private String event_title;
...
}
and in your main activity
Event ev = new Event ("EV00000001", "Movie 1")
Gson gson = new Gson();
gSon = gson.toJson(ev);
Log.i("gson", gSon);
and you will get JSON
[
{ "event_id": "EV00000001",
"event_title": "Movie 1",
}
]
What you have is an array of JSON Objects.
What the tutorial has is a JSON Object that has a property, which has an array of JSON objects.
When you look at these, here is a simple way to differentiate the two:
[] -> Array
{} -> Object
So in your code, instead of doing
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("actors");
You might want to do:
JSONArray jarray = new JSONArray(data);

How to parse JSON data without array string?

I am trying to parse data from JSON but my JSON data is an array without a string name. Here is an example:
[
{
"$id": "1",
"ClubVideoId": 1027,
"ClubId": 1,
"Title": "Brian Interview",
"ThumbURL": "url",
"VideoURL": "urll",
"DateAdded": "2014-03-25 00:00"
},
{
"$id": "2",
"ClubVideoId": 1028,
"ClubId": 1,
"Title": "Chase Interview",
"ThumbURL": "url",
"VideoURL": "urll",
"DateAdded": "2014-03-25 00:00"
},
I can seem to pass an Array without a string. Here is my code:
public void handleBlogResponse() {
mProgressBar.setVisibility(View.INVISIBLE);
if (mVideoData == null) {
updateDisplayForError();
}
else {
try {
JSONArray jsonPosts = mVideoData.getJSONArray("");
ArrayList<HashMap<String, String>> clubVideos =
new ArrayList<HashMap<String, String>>();
for (int i = 0; i < jsonPosts.length(); i++) {
JSONObject post = jsonPosts.getJSONObject(i);
String thumburl = post.getString(KEY_THUMBURL);
thumburl = Html.fromHtml(thumburl).toString();
String dateurl = post.getString(KEY_DATEADDED);
dateurl = Html.fromHtml(dateurl).toString();
HashMap<String, String> blogPost = new HashMap<String, String>();
blogPost.put(KEY_THUMBURL, thumburl);
blogPost.put(KEY_DATEADDED, dateurl);
clubVideos.add(blogPost);
}
String[] keys = {KEY_THUMBURL, KEY_DATEADDED};
int[] ids = { android.R.id.text1, android.R.id.text2 };
SimpleAdapter adapter = new SimpleAdapter(this, clubVideos,
android.R.layout.simple_list_item_2, keys, ids);
setListAdapter(adapter);
} catch (JSONException e) {
Log.e(TAG, "Exception caught!!", e);
}
}
}
Any Suggestions?
Here is where I'm pulling my json:
#Override
protected JSONObject doInBackground(Object... arg0) {
int responseCode = -1;
JSONObject jsonResponse = null;
try {
URL blogFeedUrl = new URL("http://x.com/api/Club/Getx/1/?count=" + NUMBER_OF_POSTS);
HttpURLConnection connection = (HttpURLConnection) blogFeedUrl.openConnection();
connection.connect();
responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
Reader reader = new InputStreamReader(inputStream);
int contentLength = connection.getContentLength();
char[] charArray = new char[contentLength];
reader.read(charArray);
String responseData = new String(charArray);
jsonResponse = new JSONObject(responseData);
}
else {
Log.i(TAG, "Unsuccessful HTTP Response Code: " + responseCode);
}
Log.i(TAG, "Code: " + responseCode);
}
catch (MalformedURLException e) {
logException(e);
}
catch (IOException e) {
logException(e);
}
catch (Exception e) {
logException(e);
}
return jsonResponse;
}'
how do I loop through a jsonarray?
JSONArray jr = new JSONArray("json string");
for(int i=0;i<jr.length();i++)
{
JSONObject jb = (JSONObject) jr.get(i);
String id =jb.getString("$id");
String clubvid = jb.getString("ClubVideoId");
...// similarly others
}
As squonk suggested
[ // json array node
{ // json object node
"$id": "1",
Edit:
The below should be in a thread
#Override
protected String doInBackground(Object... arg0)
{
String _response=null;
try
{
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpGet request = new HttpGet("http://sql.gamedayxtra.com/api/Club/GetClubVideos/1");
HttpResponse response = httpclient.execute(request);
HttpEntity resEntity = response.getEntity();
_response=EntityUtils.toString(resEntity);
}catch(Exception e)
{
e.printStackTrace();
}
return _response;
}
In onPostExecute
#Override
protected void onPostExecute(String _response)
JSONArray jr = new JSONArray("_response");
for(int i=0;i<jr.length();i++)
{
JSONObject jb = (JSONObject) jr.get(i);
String id =jb.getString("$id");
String clubvid = jb.getString("ClubVideoId");
...// similarly others
}

How to parse following json response in android app

I am working with webservice in an android app. I could not parse the following response in app. it always gives the
org.json.JSONException: Value
[{"METER_READING":"15","UTILITY_PLAN":"1","uname":"vinayak#triffort.com","kwh_usage":"3","meter_reading_date":"02-13-2014","ESID":"abc","METER_ID":"abc100"}]
at data of type java.lang.String cannot be converted to JSONArray.
Below is my code:
StringEntity entity = new StringEntity(jsonObject.toString(), HTTP.UTF_8);
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
BufferedReader reader =new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String jsonResultStr = reader.readLine();
JSONObject jObject = new JSONObject(jsonResultStr);
JSONArray jArray = jObject.optJSONArray("data");
I get following response from webservice
{"data":"[{\"METER_READING\":\"25\",\"UTILITY_PLAN\":\"1\",\"uname\":\"vinayak#triffort.com\",\"kwh_usage\":\"9\",\"meter_reading_date\":\"02-13-2014\",\"ESID\":\"abc\",\"METER_ID\":\"abc100\"}]"}
try using something like:
jsonResultStr = jsonResultStr.replace( "\\", "" ).replaceAll( "\"\\[", "[" ).replaceAll( "\\]\"", "]" );
JSONObject jObject = new JSONObject(jsonResultStr);
JSONArray jArray = jObject.optJSONArray("data");
I get following response
{
"data":"[{\"METER_READING\":\"25...}]"
}
The value of data is not an array; it is a string. That string is valid JSON which you could parse but why the service would do this is unclear.
So this should work:
JSONObject jObject = new JSONObject(jsonResultStr);
String parseMeAgain = jObject.optString("data");
try this simple code:
JSONObject o = new JSONObject(new JSONTokener(postResponse));
JSONArray ja = o.getJSONArray("data");
EDIT
Thanks #McDowell for observation
new JSONArray(new JSONTokener(jObject.optString("data")));
You can do this way :
JSONArray jsonArray = new JSONArray(result); // Pass your result here..
JSONObject jsonObject = jsonArray.getJSONObject(0);
String meterReading = jsonObject.getString("METER_READING");
String plan = jsonObject.getInt("UTILITY_PLAN");
String uname= jsonObject.getString("uname");
String meter_reading_date= jsonObject.getString("meter_reading_date");
String ESID= jsonObject.getString("ESID");
String METER_ID= jsonObject.getString("METER_ID");
Your json should be like this
{
"myarray": [
{
"METER_READING": "15",
"UTILITY_PLAN": "1",
"uname": "vinayak#triffort.com",
"kwh_usage": "3",
"meter_reading_date": "02-13-2014",
"ESID": "abc",
"METER_ID": "abc100"
}
]
}
for network call
public String initializeConnection(String url) {
String result = null;
JSONObject jObj;
try {
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
if(client==null){Log.i("Clinet **************** ", "Client is null");}
//post.setEntity(new UrlEncodedFormEntity(params));
HttpResponse res = client.execute(post);
result = inputStreamToString(res.getEntity().getContent()).toString();
Log.d("Result from server:", result);
jObj = new JSONObject(result.trim());
} catch (JSONException e1) {
Log.e("Json Exception", e1.toString());
} catch (ClientProtocolException e2) {
Log.e("Client Protocol", e2.toString());
} catch (IOException e3) {
Log.e("Io exception", e3.toString());
}
return result;
}
private StringBuilder inputStreamToString(InputStream is) throws UnsupportedEncodingException {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is, "iso-8859-1"),8);
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
e.printStackTrace();
}
return answer;
}
to retrive from the json
ArrayList<String> params = new ArrayList<String>();
String result = networkCall.initializeConnection(url);
jObj = new JSONObject(result);
JSONArray jArray = jObj.optJSONArray("myarray");
params.add(jArray.optString(1));
params.add(jArray.optString(2));
params.add(jArray.optString(3));
params.add(jArray.optString(4));
params.add(jArray.optString(5));
params.add(jArray.optString(6));
now the data is stored in the params you can differentiate & store it as you want

Categories

Resources