Reading Json string from a JsonObject in android [duplicate] - android

This question already has answers here:
JSONArray cannot be converted to JSONObject error
(3 answers)
Closed 6 years ago.
I am having problems; I cannot read inner string from a jsonObject. It says JsonArray cannot be converted into JsonObject.
07-26 13:01:31.910 1798-1901/com.example.phuluso.aafs I/System.out: [{"AccommoAddress":{"AddressID":12,"City":"Johannesburg","InfoUrl":null,"Lattitude":"-26.181321","Longitude":"27.99158","PostalCode":2109,"Street":"22 Ararat Str","Town":"Westdene"},"AccommoDetails":null,"AccommoID":1,"AccommoImages":null,"AccommoName":"West Dunes Properties","AccommoType":"Flat","AccredStatus":"ACCREDITED","AddressId":12,"Capacity":9,"Distance":1,"EndDate":"2017-01-01","NearestCampus":"APK","OwnerId":0,"StartDate":"2016-01-01"}]
Here's my JsonArray. I am trying to read from AccommoAddress, but I get the error below:
[{"AccommoAddress":{"AddressID":12,"City":"Johannesburg","InfoUrl":null,"Lattitude":"-26.181321","Longitude":"27.99158","PostalCode":2109,"Street":"22 Ararat Str","Town":"Westdene"},"AccommoDetails":null,"AccommoID":1,"AccommoImages":null,"AccommoName":"West Dunes Properties","AccommoType":"Flat","AccredStatus":"ACCREDITED","AddressId":12,"Capacity":9,"Distance":1,"EndDate":"2017-01-01","NearestCampus":"APK","OwnerId":0,"StartDate":"2016-01-01"}]
Here's my code
#Override
protected void onPostExecute(String result) {
progressDialog.dismiss();
List<AccommoNearAPK> data = new ArrayList<>();
progressDialog.dismiss();
JSONObject jsonResponse = null;
try
{
jsonResponse = new JSONObject(result);
JSONArray jsonMainNode = jsonResponse.optJSONArray("AccommoAddress");
/*********** Process each JSON Node ************/
int lengthJsonArr = jsonMainNode.length();
for(int i=0; i < lengthJsonArr; i++)
{
/****** Get Object for each JSON node.***********/
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
/******* Fetch node values **********/
String name = jsonChildNode.optString("Street");
String number = jsonChildNode.optString("City");
String date_added = jsonChildNode.optString("Longitude");
String lat = jsonChildNode.optString("Lattitude");
System.out.print("Street"+ name + "City" +number+ "Long" + date_added+" Lat" + lat);
Toast.makeText(MapsActivity.this, date_added + name + number + lat, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Toast.makeText(MapsActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}
}
}

"AccommoAddress" is a JSONObject not a JSONArray. So instead of this..
JSONArray jsonMainNode = jsonResponse.optJSONArray("AccommoAddress");
Try this ..
/*String Accommo = jsonResponse.getString("AccommoAddress");
JSONObject AccomoAddress = new JSONObject(Accommo);*/
//simplifying the above code
JSONObject Accomoaddress = jsonResponse.optJSONObject("AccomoAddress");
String name = AccomoAddress.getString("Street");
String number = AccomoAddress.getString("City");
String date_added = AccomoAddress.getString("Longitude");
String lat = AccomoAddress.getString("Lattitude");

Your response is a JSONArray, not a JSONObject, similarly, AccommoAddress is a JSONObject, not a JSONArray. So you need to change the lines near the top to the following:
JSONArray jsonResponse = null;
try
{
jsonResponse = new JSONArray(result);
JSONObject jsonMainNode = jsonResponse.optJSONObject("AccommoAddress");

Related

Problem with using JSON when trying get more data like "fields"

I have this code to get all information from website, I did it very well and it works, but I got stuck when trying to get "fields" from the site
This is the site url:
http://content.guardianapis.com/search?order-by=newest&show-references=author&show-tags=contributor&q=technology&show-fields=thumbnail&api-key=test
Here is the code and how can I fix it
try {
JSONObject jsonRes = new JSONObject(response);
JSONObject jsonResults = jsonRes.getJSONObject("response");
JSONArray resultsArray = jsonResults.getJSONArray("results");
for (int i = 0; i < resultsArray.length(); i++) {
JSONObject oneResult = resultsArray.getJSONObject(i);
String url = oneResult.getString("webUrl");
String webTitle = oneResult.getString("webTitle");
String section = oneResult.getString("sectionName");
String date = oneResult.getString("webPublicationDate");
date = formatDate(date);
JSONArray fields = oneResult.getJSONArray("fields");
JSONArray fieldsArray=oneResult.getJSONArray("fields");
String imageThumbnail= null;
if(fields.length()>0){
imageThumbnail=fields.getJSONObject(0).getString("thumbnail");
}
resultOfNewsData.add(new News(webTitle url, date, section, imageThumbnail));
}
} catch (JSONException e) {
Log.e("FromLoader", "Err parsing response", e);
}
Because the fields object isn't an Array is a JSON object
"fields":{"thumbnail":"https://media.guim.co.uk/fa5ae6ca7c78fdfc4ac0fe4212562e6daf4dfb3d/0_265_4032_2419/500.jpg"}
An array object should contain [ JSON1, JSON2, JSON3 ]
In your case this
JSONArray fields = oneResult.getJSONArray("fields");
becomes this
JSONObject fields = oneResult.getJSONObject("fields");
And I don't understand why are you getting the same data twice - fields and fieldsArray

Difficult to identify json data

I have json data as mentioned below.
{
"data":[
{
"Products":{
"id":"86",
"pname":"mi4",
"pcat":"9",
"subcat":"8",
"seccat":"0",
"oproduct":"1",
"pdetails":"Good phone",
"pprice":"10000",
"pdiscount":"10",
"qty":"1",
"qtytype":"GM",
"dcharge":"40",
"pimage":null,
"sname":"Easydeal",
"sid":"1100",
"size":"",
"pincode":""
}
}
]
}
I can identify array as getJSONArray("datas"). But I want to get pname and sname values.
Just reach the object
JSONObject resp=new JSONObject("response");
JSONArray data=resp.getJSONArray("data");
now if you want to get object at a particular index(say '0')
JSONObject objAt0=data.getJSONObject(0);
JSONObject products=objAt0.getJSONObject("products");
String pName=products.getString("pname");
you can similarly traverse the array
for(int i=0;i<data.lenght();i++){
JSONObject objAtI=data.getJSONObject(i);
JSONObject products=objAtI.getJSONObject("products");
String pName=products.getString("pname");
}
To get the to the key "Products" you should do:
JSONObject productsObject = YOUROBJECTNAME.getJSONArray("data").getJSONObject(0).getJSONObject("Products");
Then to get the values in productsObject you should do:
productsObject.getString("id");
productsObject.getString("pdetails");
And so on.
Try out the following code:
JSONObject object = new JSONObject(result);
JSONArray array = object.getJSONArray("data");
JSONObject object1 = array.getJSONObject(0);
JSONObject products = object1.getJSONObject("Products");
int id = object1.getInt("id");
String pname = object1.getString("pname");
This is how you get pname and sname:
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray;
try {
jsonArray = jsonObject.getJSONArray("data");
for(int counter = 0; counter <jsonArray.length(); counter++){
JSONObject jsonObject1 = jsonArray.getJSONObject(counter);
JSONObject products = jsonObject1.getJSONObject("Products");
String pname = products.getString("pname");
String sname = products.getString("sname");
}
} catch (JSONException e) {
e.printStackTrace();
}
PS: Poor JSON structure :)

How to loop through JSONArray inside JSONObject [duplicate]

This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 6 years ago.
I currently have the following JSON structure:
{
"Apps": [
{
"column1": "sample string 1",
"column2": true
},
{
"column1": "sample string 1",
"column2": true
}
],
"param": true
}
How do I get the values of the column1 and column2? What I only know how to parse is a JSONObject within a JSONArray.
JSONObject jSONObject = new JSONObject(yourStrinig);
JSONArray jArray = jSONObject.getJSONArray("Apps");
for (int i = 0; i < jArray.length(); i++) {
JSONObject childrenObject = jArray.getJSONObject(i);
String column1 = childrenObject.getString("column1");
String column2 = childrenObject.getString("column2");
}
Something like this.
// Get a reference to the JSON object
JSONObject jSONObject = new JSONObject(stringJsonResponse);
// Getting the JSON array node
JSONArray jsonAray = jSONObject.getJSONArray("Apps");
// Looping through the json array
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject childrenObject = childrenArray.getJSONObject(i);
...
...
...
}
You can take a look at how I parsed JSON data when I received similar data https://github.com/gSrikar/AskReddit/blob/master/app/src/main/java/com/example/srikar/askreddit/MainActivity.java
with this you can loop through all elements
private void showJSON(String response){
String name="";
String phone_number="";
try {
JSONObject jsonObject =new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(config.JSON_ARRAY);
for(int x=0;x<result.length();x++) {
JSONObject collegeData = result.getJSONObject(x);
name = collegeData.getString(config.KEY_NAME);
phone_number = collegeData.getString(config.KEY_PHONE_NUMBER);
//you can save your data in list here
}
} catch (JSONException e) {
e.printStackTrace();
}
}

No value For JSONstring

This is My Json String
{"Damages":[{"id":15,"rf_no":5,"state":"Print5","dmg_no":0,"town":"NEWASA","date":"16\/08\/2015","firm_name":"SHREE ENTERPRISES (NEWASE) "},{"id":36,"rf_no":7,"state":"Print7","dmg_no":0,"town":"NEWASA","date":"16\/08\/2015","firm_name":"SHREE ENTERPRISES (NEWASE) "}]}
But in Android Application its Showing No Value For Damages
This is My Android Code
JSONArray jArray = new JSONArray(json.getString("Damages"));
for (int i = 0; i < jArray.length(); i++) {
JSONObject c = jArray.getJSONObject(i);
final String id = c.getString("id");
String dmg_no =
c.getString("dmg_no");
String firm_name = c.getString("firm_name");
final String rf_no = c.getString("rf_no");
String town=c.getString("town");
String date=c.getString("date");
String State=c.getString("state");
}
Help Me Please. And Thanx In Advance.
You can try this code, to parse your json data:
try
{
JSONObject jsonObj=new JSONObject(result); // result=JSON string
if(jsonObj.has("Damages"))
{
JSONArray arrayObj=jsonObj.getJSONArray("Damages");
for(int i=0;i<arrayObj.length();i++)
{
JSONObject childArray=arrayObj.getJSONObject(i);
Log.e("", "ID "+childArray.getString("id"));
Log.e("", "Ref No"+childArray.getString("rf_no"));
// similarly you can parse rest of your tags
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Hope this helps you.
This is your mistake : JSONArray jArray = new JSONArray(json.getString("Damages"));
you are trying to get the string by name "Damages" and coverting it to JSONarray. But what you have to do is you have to convert your string to JSONObject first and then get the array named "Damages" from that json object.
Try this
String jsonString = {"Damages":[{"id":15,"rf_no":5,"state":"Print5","dmg_no":0,"town":"NEWASA","date":"16\/08\/2015","firm_name":"SHREE ENTERPRISES (NEWASE) "},{"id":36,"rf_no":7,"state":"Print7","dmg_no":0,"town":"NEWASA","date":"16\/08\/2015","firm_name":"SHREE ENTERPRISES (NEWASE) "}]}
try {
JSONObject jsonObject=new JSONObject(jsonString);
JSONArray damageArray=jsonObject.getJSONArray("Damages");
for(int i=0;i<damageArray.length();i++)
{
JSONObject obj=damageArray.getJSONObject(i);
String dmg_no = obj.getString("dmg_no");
String firm_name = obj.getString("firm_name");
final String rf_no = obj.getString("rf_no");
String town=obj.getString("town");
String date=obj.getString("date");
String State=obj.getString("state");
}
} catch (JSONException e) {
e.printStackTrace();
}
This is the problem line
JSONArray jArray = new JSONArray(json.getString("Damages"));
What are you doing is telling the program to find value of String Damages and then get array with name of that value - but there is no array called like that! Your array is already named, and the name is Damages.
To get the array you simply do
JSONArray jArray = json.getJSONArray("Damages");
assuming json is the main response you are getting

JSONObject from string on Android

l get string with answer from server. l want to do it JSONObject.
l do
JSONObject jsonObj = new JSONObject(json);
in json has
"{"sentences":[{"trans":"R\u0455R\u0491ReR\u0405","orig":"�\u0455�\u0491��\u0405","translit":"","src_translit":"R\u1E91Rg\u0300RoR\u1E90"}],"src":"ru","server_time":1}"
but jsonObj has
"{"sentences":[{"src_translit":"RẑRg̀RoRẐ","orig":"�ѕ�ґ��Ѕ","trans":"RѕRґReRЅ","translit":""}],"server_time":1,"src":"ru"}"
so how l can get value from "trans":"RѕRґReRЅ"?
PS RѕRґReRЅ it's "own" in normal charset
If you already have the jsonObj you just have to do:
try {
// Getting Array of Sentences
sentences = json.getJSONArray("sentences");
// looping through All Contacts
for(int i = 0; i < sentences.length(); i++){
JSONObject c = sentences.getJSONObject(i);
// get the value from trans
String trans = c.getString("trans");
//now you should save this string in an array
}
} catch (JSONException e) {
e.printStackTrace();
}
try this
JSONObject jsonObj = new JSONObject(json);
JSONArray sentences = jsonObj.getJSONArray("sentences");
for(int i=0;i<sentences.length();i++){
JSONObject number = sentences.getJSONObject(i);
String transValue = number.getString("trans");
}
First you have to remove single quote form starting and from ending of your JSON string (json), by this your JSON will be a valid json for this you have to do like :
json= json.substring(1, json.length()-1);
After that you do like this :
JSONObject oJsonObject = new JSONObject(json);
JSONArray oJsonArray = oJsonObject.getJSONArray("sentences");
for(int i=0; i<oJsonArray.length(); i++)
{
JSONObject oJsonObject1 = oJsonArray.getJSONObject(i);
String transValue = oJsonObject1 .getString("trans");
}

Categories

Resources