I have a jsonArray response. I need to read this response which contains with 3 jsonArrays.
This is the json response. This is a GET request and send by Volley request.
[
"0x9000",
[
[
"D3521",
"abc"
],
[
"D4212",
"def"
],
[
"D2715",
"hij ."
],
[
"D2366",
"klm"
],
[
"D3660",
"nopq"
]
]
]
Here is the code that I have tried I'm sending a string request.
try{
RequestQueue MyRequestQueue = Volley.newRequestQueue(this);
final String endpoint = "getdoctors";
final String url = SettingsConfig.IP + endpoint;
StringRequest MyStringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
android.util.Log.d("print response",response);
try {
JSONArray jsonArray = new JSONArray(response);
for (int i=0; i<jsonArray.length(); i++){
JSONArray dataArray = (JSONArray) jsonArray;
String code = dataArray.getString(i);
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("Provider Inquiry","JSON error:" + e.getMessage());
Intent intent = new Intent(EChannellingInfoActivity.this,MainMenuActivity.class);
startActivity(intent);
finish();
}
}
}, new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
#Override
public void onErrorResponse(VolleyError error) {
android.util.Log.d("print error", error.toString());
//This code is executed if there is an error.
}
});
MyStringRequest.setRetryPolicy(new DefaultRetryPolicy(0, 0, DefaultRetryPolicy.DEFAULT_TIMEOUT_MS));
MyRequestQueue.add(MyStringRequest);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
There are 3 jsonArrays in this response. How can I categorize/read them one by one.
First Create a class which contains the inner instance
public class InnerObj
{
String id;
String name;
}
Then Create the Class of outer object using the inner object
public class OuterObj
{
String size;
InnerObj values[];
}
Now you can use the OuterObj class as the responseType map it to the response from volley
I want to parse the following JSON file but is starting with [ indicating to me that is an array.
When JSON string starting with [ means the string is JSONArray
how to modify the parser to parse this file?
1. Convert JSON String to JSONArray instead of JSONObject:
JSONArray jsonArray = new JSONArray(json);
2. Change return type of getJSONFromUrl method to JSONArray from JSONObject
3. In doInBackground get response from getJSONFromUrl method in JSONArray:
JSONArray jsonArray = jParser.getJSONFromUrl(URL);
Here is further answers LINK
Here is you can parse your JSON array
JSONArray jsonArray = new JSONArray(response);
String str = (String) jsonArray.get(0);
JSONArray arrayTwo = jsonArray.getJSONArray(1);
for (int i=0; i<arrayTwo.length(); i++){
JSONArray dataArray = arrayTwo.getJSONArray(i);
String code = dataArray.getString(i);
}
Related
I'm using JSONObject to parse the JSON file and get its contents. Everything goes fine but tags aren't showing in the RecyclerView.
Here's the code :
private void direct_url(){
v_title = findViewById(R.id.vid_title);
String url = kw_url_holder.getText().toString();
String server_tag_url = "https://server.com/json.json";
StringRequest request = new StringRequest(Request.Method.GET, server_tag_url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
String title,views,likes,dislikes,publishedon,duration;
JSONObject object=new JSONObject(response);
title = object.getString("title");
v_title.setText(title);
JSONArray tagsJsonArray = object.getJSONArray("tags");
for(int i=0; i<tagsJsonArray.length();i++){
try {
JSONObject tagObj = new JSONObject();
tagObj = tagsJsonArray.getJSONObject(i);
TagUrlResultsModel tagUrlResultsModel = new TagUrlResultsModel();
tagUrlResultsModel.setV_tags(tagObj.getString(String.valueOf(i)));
url_result.add(tagUrlResultsModel);
}catch (JSONException e){
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("error",error.toString());
}
});
url_queue = Volley.newRequestQueue(tags.this);
url_queue.add(request);
}
The JSON:
{
"title": "The Title",
"tags": ["tag1", "tag2"]
}
An error in the logs:
Error: java.lang.String cannot be converted to JSONObject
The problem is inside your for loop in:
JSONObject tagObj = new JSONObject();
tagObj = tagsJsonArray.getJSONObject(i);
TagUrlResultsModel tagUrlResultsModel = new TagUrlResultsModel();
tagUrlResultsModel.setV_tags(tagObj.getString(String.valueOf(i)));
url_result.add(tagUrlResultsModel);
It should be
String tag;
tag = tagsJsonArray.getString(i);
TagUrlResultsModel tagUrlResultsModel = new TagUrlResultsModel();
tagUrlResultsModel.setV_tags(tag);
url_result.add(tagUrlResultsModel);
Using getString() instead of getJSONObject() as the content of that JSONArray is just strings.
That's why you are getting in that catch:
Error: java.lang.String cannot be converted to JSONObject
I am having an error of data of type org.json.JSONObject cannot be converted to JSONArray
Here is the look of my response
{
"success": "true",
"data": {
"email": "sample#gmail.com",
"session_code": "samplesession"
}
}
here is my code
StringRequest stringRequest = new StringRequest(Request.Method.POST,Config.login, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
JSONArray details = obj.getJSONArray("data");
if (status_code == 200) {
Log.d("success_to",response);
for (int i=0; i<details.length(); i++) {
JSONObject object = details.getJSONObject(i);
String email = object.getString("email");
Log.d("sample_email", email);
}
finish();
startActivity(new Intent(getApplicationContext(), Profile.class));
}else{
Log.d("error_to","error 404 na");
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
i am still new in android and i am still learning the process, can somebody help me with my problem, this really is killing my time in fixing this error.
There is no array in your json so try like below
JSONObject obj = new JSONObject(response);
JSONObject data=obj.optJSONObject("data");
String email = data.getString("email");
Remove below line from your code
JSONArray details = obj.getJSONArray("data");
for (int i=0; i<details.length(); i++) {
JSONObject object = details.getJSONObject(i);
String email = object.getString("email");
Log.d("sample_email", email);
}
could anyone help me set up parsing for this JSON data file.
I want to get each train departure. The structure is departures -> all - > 0,1,2,3 etc... Thanks
I am trying to get certain strings such as time, destination and platform and then display it in a list for each departure.
private void jsonParse()
{
String url = key;
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("REST", response.toString());
try {
JSONArray jsonArray= response.getJSONArray("departures");
Log.d("REST", jsonArray.toString());
for(int i = 0; i < jsonArray.length(); i++)
{
JSONObject departure = jsonArray.getJSONObject(i);
JSONObject all = departure.getJSONObject("all");
String Mode = all.getString("Mode");
TextViewResult.append(Mode + "\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
Queue.add(request);
}
If I have understood correctly, you are getting no results, right?
The JSON objects (0, 1, ...) are children of "all", which is a JSONArray, not a JSONObject. And "departures" seems to be a JSONObject and not a JSONArray. You should:
Get "departures" as a JSONObject out of the loop.
Get "all" as a JSONArray from teh previous one, as it is a child of "departures", and do this also out of the loop.
Iterate over the previous JSONArray in the loop, obtaining the JSONObject's which represent one departure each.
So, the block inside the try would look like this:
//logging omitted
JSONObject departuresJSONObj = response.getJSONObject("departures");
JSONArray allJSONArr = departuresJSONObj.getJSONArray("all");
JSONObject departureJSONObj;
String mode;
for (Object departureObj : allJSONArr) {
if (departureObj instanceof JSONObject) {
departureJSONObj = (JSONObject) departureObj;
mode = departureJSONObj.getString("mode"); //mode is lowercase in the JSON
TextViewResult.append(mode + "\n");
}
}
Hope this helps.
I'm trying to build a Quiz game for fun but I'm struggling to figure out how to pull the string I want from a JSONArray in Android Studio
I'm getting the Log of the "JSON" and "results" come up in Logcat but I can't seem to work out how to set my mQuestion variable to the relevant string.
The JSON
{
"response_code":0,
"results":[{
"category":"General Knowledge",
"type":"multiple",
"difficulty":"medium",
"question":"According to the BBPA, what is the most common pub name in the UK?",
"correct_answer":"Red Lion",
"incorrect_answers": [
"Royal Oak",
"White Hart",
"King's Head"
]
}]
}
My code
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.i("JSON", s);
try {
JSONObject jsonObject = new JSONObject(s);
String results = jsonObject.getString("results");
Log.i("results", results);
JSONArray arr = new JSONArray(results);
for (int i = 0; i < arr.length(); i++) {
mQuestion = arr.getJSONObject(3).getString("question");
Log.i("Question", mQuestion);
}
} catch (Exception e) {
e.printStackTrace();
}
}
I get in the Logcat is W/System.err: at ...MainActivity$getQuestion.onPostExecute(MainActivity.java:67)
67 is the line containing "mQuestion = arr.getJSONObject(3).getString("question");"
You need to use i you declare in loop:
mQuestion = arr.getJSONObject(i).getString("question");
You are parsing JsonObject and JsonArray wrongly.
use this code:
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.i("JSON", s);
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray results = jsonObject.getJSONArray("results");
JSONObject jsonObject1 = results.getJSONObject(0);
Log.i("results", results.toString());
String mQuestion = jsonObject1.getString("question");
Log.i("Question", mQuestion);
} catch (Exception e) {
e.printStackTrace();
}
}
I am a beginner in the use of JSON.
So I try to extract the url of an image from a JSON reply.
Here is the code that allows me to get an Array:
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(getActivity());
//String url ="http://www.google.com";
String url = "http://ws.audioscrobbler.com/2.0/?method=album.search&album="+albumName+"&api_key=c51f8eb36bad&format=json";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
//mTextView.setText("Response is: "+ response.substring(0,500));
Log.i("RESPONSE","Response is: "+ response);
JSONObject jsono = new JSONObject();
try {
jsono = new JSONObject(response);
//String url = jsono.getString("results");
//Log.i("RESPONSE",url);
} catch (JSONException e) {
e.printStackTrace();
Log.d ("RESPONSE",e.getMessage());
}
JSONArray jsonArray = new JSONArray();
try {
jsonArray = jsono.getJSONObject("results").getJSONObject("albummatches").getJSONArray("album");
} catch (JSONException e) {
e.printStackTrace();
Log.d ("RESPONSE",e.getMessage());
}
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = new JSONObject();
try {
object = jsonArray.getJSONObject(i);
Log.i("RESPONSE",object.getString("image"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("RESPONSE","That didn't work!");
}
});
queue.add(stringRequest);
And here is the structure of this part in the JSON answer:
{
"album": [
{
"name": "DD Y Ponle Play",
"artist": "Jumbo",
"id": "2528039",
"url": "http://www.last.fm/music/Jumbo/DD+Y+Ponle+Play",
"image": [
{
"#text": "http://images.amazon.com/images/P/B00005LN6S.01._SCMZZZZZZZ_.jpg",
"size": "small"
},
{
"#text": "http://images.amazon.com/images/P/B00005LN6S.01._SCMZZZZZZZ_.jpg",
"size": "medium"
},
{
"#text": "http://images.amazon.com/images/P/B00005LN6S.01._SCMZZZZZZZ_.jpg",
"size": "large"
},
{
"#text": "http://images.amazon.com/images/P/B00005LN6S.01._SCMZZZZZZZ_.jpg",
"size": "extralarge"
}
]
}
]
}
How to get the url of an image for a given size?
Thank you very much for your suggestions.
You can use google GSON for this. Import it as a dependency
First create an album class.
public class Albums {
private List<Album> album;
public List<Album> getAlbum() {
return album;
}
public class Album{
private String name;
private String artist;
private String id;
private String url;
public String getName() {
return name;
}
public String getArtist() {
return artist;
}
public String getId() {
return id;
}
public String getUrl() {
return url;
}
public List<Image> getImage() {
return image;
}
public class Image {
#SerializedName("#text")
private String text;
private String size;
public String getText() {
return text;
}
public String getSize() {
return size;
}
}
private List<Image> image;
}
}
Now in your code where you get the above JSON object try this code below
Gson gson = new Gson();
// Im assuming "response" as the above JSON object
Albums albums = gson.fromJson(response.optString("album"),Albums.class);
This will map your json to java object.(Note: You can remove unwanted objects from the POJO as you like)
You can get the image using the getter functions
JSON is nothing but a key-value representation. It's not hard to get a hang of it. Your code should be something like this,
Update: This will only print URL's which have size = medium
String response = "{\"album\":[{\"name\":\"DD Y Ponle Play\",\"artist\":\"Jumbo\",\"id\":\"2528039\",\"url\":\"http://www.last.fm/music/Jumbo/DD+Y+Ponle+Play\",\"image\":[{\"#text\":\"http://images.amazon.com/images/P/B00005LN6S.01._SCMZZZZZZZ_.jpg\",\"size\":\"small\"},{\"#text\":\"http://images.amazon.com/images/P/B00005LN6S.01._SCMZZZZZZZ_.jpg\",\"size\":\"medium\"},{\"#text\":\"http://images.amazon.com/images/P/B00005LN6S.01._SCMZZZZZZZ_.jpg\",\"size\":\"large\"},{\"#text\":\"http://images.amazon.com/images/P/B00005LN6S.01._SCMZZZZZZZ_.jpg\",\"size\":\"extralarge\"}]}]}";
JSONObject myObject = new JSONObject(response);
JSONArray myArray = myObject.getJSONArray( "album" );
for(int i=0; i<myArray.length(); i++)
{
JSONObject myIterator = myArray.getJSONObject( i );
JSONArray arrayOne = myIterator.getJSONArray( "image" );
for(int j=0; j<arrayOne.length(); j++)
{
JSONObject myInnerIterator = arrayOne.getJSONObject( j );
if(myInnerIterator.has( "size" ))//check if 'size' key is present
if(myInnerIterator.getString( "size" ).equalsIgnoreCase( "medium" ))
System.out.println( myInnerIterator.getString( "#text" ) );
}
}
As mentioned by Raghunandan, you're extracting a JSONObject, when you need to be extracting a JSONArray, and then from that array, you can extract a JSONObject.
Try using a library such as GSON to make this task easier, or refer to this tiny JSON library I wrote.
It's pretty simple actually to parse a JSON array:
JSONArray jsonarray = new JSONArray("album");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String url = jsonobject.getString("url");
}
Hope it helps!!!
To find the url of the images "medium" I did like this:
ArrayList<String> listUrl = new ArrayList<String>();
for(int i=0; i<jsonArray.length(); i++)
{
JSONObject myIterator = null;
try {
myIterator = jsonArray.getJSONObject( i );
JSONArray arrayOne = myIterator.getJSONArray( "image" );
for(int j=0; j<arrayOne.length(); j++)
{
JSONObject myInnerIterator = arrayOne.getJSONObject( j );
String s = myInnerIterator.getString( "size" )+myInnerIterator.getString("#text");
if (s.contains("medium") && s.contains("https")){
listUrl.add (s.replace("medium",""));
Log.i("RESPONSE",s.replace("medium",""));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
I think there must be much better ... but it does the job!