org.json.JSONException: No value - android

org.json.JSONException: No value in array
StringRequest req = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String s) {
try {
questionsList = new ArrayList<QuestionsBean>();
JSONObject jsonObject = new JSONObject(s);
JSONArray question = jsonObject.getJSONArray("questions");
for (int i = 0; i < question.length(); i++) {
JSONObject x = question.getJSONObject(i);
QuestionsBean u = new QuestionsBean();
u.setDate(x.getString("date"));
u.setQuestion(x.getString("question_text"));
JSONObject bject = new JSONObject();
JSONArray answers = bject.getJSONArray("answers");
for (int j = 0; j < answers.length(); j++) {
JSONObject xx = answers.getJSONObject(i);
u.setAnswer_body(xx.getString("Answer_body"));
}
questionsList.add(u);

You are not calling getJSONArray on the correct JSONObject. Use
JSONArray answers = x.getJSONArray("answers");
Also, since your JSONArray could be null, use optJSONArray to avoid the exception and check if it's null before continuing.
Something like
JSONArray answers = x.optJSONArray("answers");
if (answers != null) {
// for loop
}

JSONObject bject = new JSONObject();
JSONArray answers = bject.getJSONArray("answers");
You constructed here an empty JSONObject, so it is normal what it cannot find 'answers' in it.

Related

Parsing Nested JSON Objects using Volley

I had gone through most of the answers in stack overflow and tried some of the answers which didn't work.
It is a response from a SOAP API.
I tried by using
JSONObject obj = new JSONObject(response);
JSONArray heroArray = new JSONArray();
JSONObject one = obj.getJSONObject("getProjectDetailsResult");
JSONObject two = one.getJSONObject("NewDataSet");
heroArray= two.getJSONArray("Rec");
for (int i = 0; i < heroArray.length(); i++) {
JSONObject heroObject = heroArray.getJSONObject(i);
Hero hero = new Hero(heroObject.getString("decProjectID"),
heroObject.getString("chvProjectNameEng"));
This is what I am getting in the LogCat
2019-12-08 15:00:47.572 6134-6134/net.marvelheroes W/System.err: org.json.JSONException: Value {"decProjectID":"100300230049","intProjectSlNo":"49",......"percentage":"0"} at Rec of type org.json.JSONObject cannot be converted to JSONArray
2019-12-08 15:00:47.572 6134-6134/net.marvelheroes W/System.err: at org.json.JSON.typeMismatch(JSON.java:100)
2019-12-08 15:00:47.572 6134-6134/net.marvelheroes W/System.err: at org.json.JSONObject.getJSONArray(JSONObject.java:588)
I tried
JSONObject heroArray = new JSONObject();
JSONObject one = obj.getJSONObject("getProjectDetailsResult");
JSONObject two = one.getJSONObject("NewDataSet");
heroArray= two.getJSONObject("Rec");
But I am getting error for the rest of the code. I am testing this with the sample from https://www.simplifiedcoding.net/android-volley-tutorial-fetch-json/
Rec is not JSONArray, it's JSONObject. Try using
try {
JSONObject obj = new JSONObject(response);
JSONObject one = obj.getJSONObject("getProjectDetailsResult");
JSONObject two = one.getJSONObject("NewDataSet");
if(two.get("Rec") instanceof JSONArray) {
JSONArray heroArray = two.getJSONArray("Rec");
for (int i = 0; i < heroArray.length(); i++) {
JSONObject heroObject = heroArray.getJSONObject(i);
Hero hero = new Hero(heroObject.getString("decProjectID"),
heroObject.getString("intProjectSlNo"),
heroObject.getString("chvProjectName"),
heroObject.getString("chvProjectNameEng"),
heroObject.getString("chrProjCatCode"),
heroObject.getString("chvEngProjCategory"),
heroObject.getString("nchvSecType"),
heroObject.getString("chvEngSecType"),
heroObject.getString("chvImplOfficerDesg"),
heroObject.getString("chvImplOfficerDesgEng"),
heroObject.getString("singleYrAmt"),
heroObject.getString("TotExp"),
heroObject.getString("percentage"));
heroList.add(hero);
}
} else {
JSONObject heroObject = two.getJSONObject("Rec");
Hero hero = new Hero(heroObject.getString("decProjectID"),
heroObject.getString("intProjectSlNo"),
heroObject.getString("chvProjectName"),
heroObject.getString("chvProjectNameEng"),
heroObject.getString("chrProjCatCode"),
heroObject.getString("chvEngProjCategory"),
heroObject.getString("nchvSecType"),
heroObject.getString("chvEngSecType"),
heroObject.getString("chvImplOfficerDesg"),
heroObject.getString("chvImplOfficerDesgEng"),
heroObject.getString("singleYrAmt"),
heroObject.getString("TotExp"),
heroObject.getString("percentage"));
heroList.add(hero);
}
} catch ( Exception ex) {
ex.printStackTrace();
}

array of objects

For post method in android
I have to send array of objects.
I am retrieving elements from an arrayList and putting that retrieved element in JSONObject and than putting that in JSONobject in JSONArray.
JSONArray ccArray = new JSONArray();
{
JSONObject object = new JSONObject();
if (ccArrayList.size() != 0) {
for (int i = 0; i < ccArrayList.size(); i++) {
object.put("emailId", ccArrayList.get(i));
ccArray.put(object);
}
} else {
object.put("", "");
}
}
When there are more than 2 or more than 2 elements in arraylist it is adding the last element in ccrray as many times as their are elements in the list.
output :
"cc":[{"emailId":"f#j.com"},{"emailId":"f#j.com"}]
Change code like this
JSONObject obj = new JSONObject();
JSONArray ccArray = new JSONArray();
for (int i = 0; i < ccArrayList.size(); i++) {
JSONObject object = new JSONObject();
if (ccArrayList.size() != 0) {
object.put("emailId", ccArrayList.get(i));
ccArray.put(object);
} else {
object.put("", "");
}
}
obj.put("cc",ccArray);
Code:-
ArrayList<String> ccArrayList = new ArrayList<String>();
ccArrayList.add("abc#xyz.com");
ccArrayList.add("abc#xyz.com");
ccArrayList.add("abc#xyz.com");
ccArrayList.add("abc#xyz.com");
ccArrayList.add("abc#xyz.com");
JSONArray ccArray = new JSONArray();
if(ccArrayList.size()>0){
for(int i=0;i<ccArrayList.size();i++){
JSONObject object = new JSONObject();
try {
object.put("emailId", ccArrayList.get(i));
} catch (JSONException e) {
e.printStackTrace();
}
ccArray.put(object);
}
}
Output:-
ccArray: [{"emailId":"abc#xyz.com"},{"emailId":"abc#xyz.com"},{"emailId":"abc#xyz.com"},{"emailId":"abc#xyz.com"},{"emailId":"abc#xyz.com"}]
That's because you declared JSONObject object = new JSONObject(); outside the for loop, so each time it loops the object adds a new JSONObject and also does the array. Try keeping it within the loop:
JSONArray ccArray = new JSONArray();
for (int i = 0; i < ccArrayList.size(); i++) {
JSONObject object = new JSONObject();
object.put("emailId", ccArrayList.get(i));
ccArray.put(object);
}

JSONException while using last.fm API in android

JSON :
{"results":{"opensearch:Query":{"#text":"","role":"request","searchTerms":"Rose","startPage":"1"},"opensearch:totalResults":"102325","opensearch:startIndex":"0","opensearch:itemsPerPage":"1","artistmatches":{"artist":[{"name":"Guns N' Roses","listeners":"3198315","mbid":"eeb1195b-f213-4ce1-b28c-8565211f8e43","url":"https://www.last.fm/music/Guns+N%27+Roses","streamable":"0","image":[{"#text":"https://lastfm-img2.akamaized.net/i/u/34s/7d102ebcf4184bb1ae2b851efcbceb30.png","size":"small"},{"#text":"https://lastfm-img2.akamaized.net/i/u/64s/7d102ebcf4184bb1ae2b851efcbceb30.png","size":"medium"},{"#text":"https://lastfm-img2.akamaized.net/i/u/174s/7d102ebcf4184bb1ae2b851efcbceb30.png","size":"large"},{"#text":"https://lastfm-img2.akamaized.net/i/u/300x300/7d102ebcf4184bb1ae2b851efcbceb30.png","size":"extralarge"},{"#text":"https://lastfm-img2.akamaized.net/i/u/300x300/7d102ebcf4184bb1ae2b851efcbceb30.png","size":"mega"}]}]},"#attr":{"for":"Rose"}}}
I am unable to fetch the artist details using this JSON.
I would like to know the format to use this JSON in Volley android.
Code:
final JsonArrayRequest jsonArrayRequest = new
JsonArrayRequest(Request.Method.GET,url,null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject object = response.getJSONObject(i);
JSONObject obj1 = object.getJSONObject("results");
JSONObject obj2 = obj1.getJSONObject("artistmatches");
JSONArray m_jArry = obj2.getJSONArray("artist");
for (i = 0; i < m_jArry.length(); i++)
{
JSONObject obj4 = m_jArry.getJSONObject(i);
String name=obj4.getString("name");
String mbid=obj4.getString("mbid");
String url=obj4.getString("url");
}
You need to use JSONObject as Response rather than JSONArray because, you're receiving JSONObject from API.
Use like below:
JsonArrayRequest(Request.Method.GET,url,null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//for (int i = 0; i < response.length(); i++) { Removed for loop
try {
JSONObject object = response; //We're using JSONObject from API here
JSONObject obj1 = object.getJSONObject("results");
JSONObject obj2 = obj1.getJSONObject("artistmatches");
JSONArray m_jArry = obj2.getJSONArray("artist");
for (i = 0; i < m_jArry.length(); i++)
{
JSONObject obj4 = m_jArry.getJSONObject(i);
String name=obj4.getString("name");
String mbid=obj4.getString("mbid");
String url=obj4.getString("url");
}
Try this....i have edited your jsonResponse
JSONObject jsonObject = new JSONObject(response);
JSONObject results = jsonObject.getJSONObject("results");
JSONObject opensearch = results.getJSONObject("opensearch:Query");
String text = opensearch.getString("#text");//after this get your all string of "opensearch:Query" object same way
String totalResults=results.getString("opensearch:totalResults");////after this get your all other string like "opensearch:startIndex" and "opensearch:itemsPerPage" of "results" object same way
JSONObject artistmatches = results.getJSONObject("artistmatches");
JSONArray artist = artistmatches.getJSONArray("artist");
JSONArray image = artist.getJSONArray("image");
for (int i = 0; i < artist.length(); i++) {
JSONObject allartist = artist.getJSONObject(i);
String name=artist.getString("name"); // same you can get all strings like "listeners","mbid".. of artist array
//by this you will get images array
for (int j = 0; j < image.length(); j++) {
JSONObject allimage = image.getJSONObject(i);
String imageText=allimage.getString("#text");
String size=allimage.getString("size");
}

how to post nested Json Array to server?

Hi i want to post this a json array which has two json arrays of Integers in them to server using JsonObject
"job_experiences": [
{
"job_category": [Integer],
"experience_level": [Integer]
}
]
JsonArray list = new JsonArray();
for (int i = 0; i < selectedJobs.size(); i++) {
list.add(selectedJobs.get(i));
}
JsonArray list2 = new JsonArray();
for (int i = 0; i < selectedJobs.size(); i++) {
list2.add(selectedJobs.get(i));
}
JsonObject postData = new JsonObject();
postData.add("job_category", list);
postData.add("experience_level", list2);
Please use JSONObject instead of JsonObject and JSONArray instead of JsonArray,
Try below approach and check
JSONArray list = new JSONArray();
for (int i = 0; i < selectedJobs.size(); i++) {
list.put(selectedJobs.get(i));
}
JSONArray list2 = new JSONArray();
for (int i = 0; i < selectedJobs.size(); i++) {
list2.put(selectedJobs.get(i));
}
JSONObject postData = new JSONObject();
try {
postData.put("job_category", list);
postData.put("experience_level", list2);
JSONArray job_experiences = new JSONArray();
job_experiences.put(postData);
JSONObject jsonObject_job_experiences = new JSONObject();
jsonObject_job_experiences.put("job_experiences", job_experiences);
Log.e("jsonObject_job_exp", jsonObject_job_experiences.toString());
} catch (JSONException e) {
e.printStackTrace();
}
and in the log you can see the final JSONObject

Create json fromat in android

How can I create a in android json like this.I can create the json object but still facing some problem to make like this.
{
"IncidentDetails": {
"StreetId": "370","StartDate":"21-03-2015","EndDate":"24-03-2015",
"ImageDetails": [
{
"PhoneImageUrl": "\/storage\/sdcard0\/Pictures\/GestiónDeIncidencias\/IMG_20150321_215458_-926186234.jpg",
"Base64ImageData": "Ioop9RLYCKTAIzRRSGIVGw9s1hvw5HvRRVRYtixan+daM2pCQ\/PH40nQ0uOOKM880guIQTmm044xnNNx",
},
{
"PhoneImageUrl": "\/storage\/sdcard0\/Pictures\/GestiónDeIncidencias\/IMG_20150321_215458_-926186234.jpg",
"Base64ImageData": "Ioop9RLYCKTAIzRRSGIVGw9s1hvw5HvRRVRYtixan+daM2pCQ\/PH40nQ0uOOKM880guIQTmm044xnNNx",
},
{
"PhoneImageUrl": "\/storage\/sdcard0\/Pictures\/GestiónDeIncidencias\/IMG_20150321_215458_-926186234.jpg",
"Base64ImageData": "Ioop9RLYCKTAIzRRSGIVGw9s1hvw5HvRRVRYtixan+daM2pCQ\/PH40nQ0uOOKM880guIQTmm044xnNNx",
}
]}
}
What I tried in my android code just have a look it giving totally different output
JSONArray jsonArray = new JSONArray();
JSONObject IncidentDetails = new JSONObject();
try
{
IncidentDetails.put("StartDate", EditTextStartText.getText().toString());
IncidentDetails.put("EndDate", EditTextEndText.getText().toString());
IncidentDetails.put("StreetId", StreetId);
jsonArray.put(IncidentDetails);
for(int i=0; i<length; i++)
{
JSONObject ImageDetails = new JSONObject();
ImageDetails.put("Base64ImageData", getBase64Image(ReusableClass.imgUrl.get(i)));
ImageDetails.put("PhoneImageUrl", ReusableClass.imgUrl.get(i));
jsonArray.put(ImageDetails);
}
JSONObject IncidentDetailsObj = new JSONObject();
IncidentDetailsObj.put("IncidentDetails", jsonArray);
String jsonStr = IncidentDetailsObj.toString();
My current output
{"IncidentDetails":[{"StreetId":"370","StartDate":"18-03-2015","EndDate":""},{"PhoneImageUrl":"\/storage\/sdcard0\/Pictures\/GestiónDeIncidencias\/IMG_20150318_171451_1389057690.jpg","Base64ImageData":"\/9j\/4AAQSkZJRgABAQAAAQABAAD\/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkz\nODdASFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2P\/2wBDARESEhgVGC8aGi9jQjhCY2NjY2Nj\nY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2P\/wAA"},{"PhoneImageUrl":"\/storage\/sdcard0\/Pictures\/GestiónDeIncidencias\/IMG_20150318_171451_1389057690.jpg","Base64ImageData":"\/9j\/4AAQSkZJRgABAQAAAQABAAD\/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkz\nODdASFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2P\/2wBDARESEhgVGC8aGi9jQjhCY2NjY2Nj\nY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2P\/wAA"}]}
Use this
JSONArray jsonArray = new JSONArray();
JSONObject IncidentDetails = new JSONObject();
try
{
IncidentDetails.put("StartDate", EditTextStartText.getText().toString());
IncidentDetails.put("EndDate", EditTextEndText.getText().toString());
IncidentDetails.put("StreetId", StreetId);
for(int i=0; i<length; i++)
{
JSONObject ImageDetails = new JSONObject();
ImageDetails.put("Base64ImageData", getBase64Image(ReusableClass.imgUrl.get(i)));
ImageDetails.put("PhoneImageUrl", ReusableClass.imgUrl.get(i));
jsonArray.put(ImageDetails);
}
IncidentDetails.put("ImageDetails", jsonArray);
JSONObject IncidentDetailsObj = new JSONObject();
IncidentDetailsObj.put("IncidentDetails", IncidentDetails);
String jsonStr = IncidentDetailsObj.toString();
see answer with comments,
//* IncidentalDetial is an object not an array
JSONObject IncidentDetails = new JSONObject();
//* add the first three elements
IncidentDetails.put("StartDate", EditTextStartText.getText().toString());
IncidentDetails.put("EndDate", EditTextEndText.getText().toString());
IncidentDetails.put("StreetId", StreetId);
//* contruct the imagedetails array
JSONArray jsonArray = new JSONArray();
for(int i=0; i<length; i++)
{
JSONObject ImageDetails = new JSONObject();
ImageDetails.put("Base64ImageData", getBase64Image(ReusableClass.imgUrl.get(i)));
ImageDetails.put("PhoneImageUrl", ReusableClass.imgUrl.get(i));
jsonArray.put(ImageDetails);
}
//* add the imagedetails array to the incidentDetials object
IncidentDetails.put(jsonArray);
JSONObject IncidentDetailsObj = new JSONObject();
IncidentDetailsObj .put(IncidentDetails);
String jsonStr = IncidentDetailsObj.toString();
Notice that that this is very common scenario, so there has to be some library that deals it for you :)
I recommend https://code.google.com/p/google-gson - GSON. All you have to do is to prepare POJO class that describes JSON, in your case:
public class IncidentDetails {
IncidentDetails incidentDetails;
}
public class IncidentDetails {
String streetId;
String startDate;
String endDate;
ImageDetails imageDetails;
}
Then do the same with ImageDetails. All you have to do then is to create GSON with proper naming policy (it converts automaticcaly class fields names to JSON).
gson.toJson(incidentDetails) creates String you desire. gson.fromString(String json) will create IncidentDetails object from json string.

Categories

Resources