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.
Related
I'm trying to convert a string array list to a JSONArray then send it to a remote server
I expect it to send my array in a JSONarray format
this is the error "'java.lang.String org.json.JSONObject.getString(java.lang.String)' on a null object reference"
My array got 2 elements,
when i try to fetch them in the log.d : list ja [null,null]
This is the code i'm using
public void sendCommande (){
bt_newCommande.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//----------------------------------
StringRequest stringRequest = new StringRequest(Request.Method.POST,url_ProdCommande, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG,"element envoie !");
//listProRest.clear();
//adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<String,String>();
JSONArray ja = new JSONArray(db.afficherTousProduit());
Log.d(TAG,"list ja "+ja.toString());
for(int i =0;i<ja.length();i++){
JSONObject j = ja.optJSONObject(i);
/*
try {
params.put("idProduit",j.getString(db.afficherTousProduit().get(i).getIdProduct()));
params.put("qte",j.getString(String.valueOf(db.afficherTousProduit().get(i).getQtePro())));
params.put("heure",j.getString(db.afficherTousProduit().get(i).gethCollete()));
params.put("date",j.getString(db.afficherTousProduit().get(i).getDateCollete()));
} catch (JSONException e) {
e.printStackTrace();
}
*/
}
//params.put("id",arrayList.get(position).getIdProduct());
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
});
}
It looks like something is going wrong with
db.afficherTousProduit().get(i).getIdProduct()
I would set a breakpoint and check that the db is returning what you expect it to return.
From looking at your code, it seems like you are doing extra work converting to and from JSON several times. I could be wrong, but I think this could be cleaned up like so:
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<String,String>();
JSONArray ja = new JSONArray(db.afficherTousProduit());
Log.d(TAG,"list ja "+ja.toString());
// Begin iterating through the JSON Array
for (int i=0; i < arr.length(); i++) {
// Get current JSON Object at index i
JSONObject j = arr.getJSONObject(i)
try {
// Return the specified value associated with the String for the current object
params.put("key",j.getJsonString("key");
} catch (JSONException e) {
e.printStackTrace();
}
}
//params.put("id",arrayList.get(position).getIdProduct());
return params;
}
It shouldn't require more than one db access to get the json array, and then it's a simple matter of iterating through each object and grabbing what you need from it. Check out the Java docs for more info.
Attempting to load specific api through twitch headers. This Code has always worked in the past in fact still works but is pulling another user that i have replaced.
Tried to use android volley url to string, tried Variable
tried to clear cache in code, in app, and in device
this appears to be related to the volley's cache but i cant seem to clear it.
I dont feel it is api related otherwise wouldn't pull the old information either. or at least wouldn't work after cache was cleared.
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
queue.getCache().clear();
String url = "https://api.twitch.tv/helix/users?login=Twitchuser";
// Request a string response from the provided URL.
final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(com.android.volley.Request.Method.GET, url, null, new
Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject jsonObject = response;
JSONArray JA = jsonObject.getJSONArray("data");
for (int i = 0; i < response.length(); i++) {
JSONObject object = JA.getJSONObject(i);
String bio = object.getString("description");
mTextView2.append(bio);
}
JSONObject jsonObject2 = response;
JSONArray JA2 = jsonObject2.getJSONArray("data");
for (int i = 0; i < response.length(); i++) {
JSONObject object = JA2.getJSONObject(i);
String name =
object.getString("display_name");
mTextView.append(name);
}
JSONObject jsonObject3 = response;
JSONArray JA3 = jsonObject3.getJSONArray("data");
for (int i = 0; i < response.length(); i++) {
JSONObject object = JA3.getJSONObject(i);
String Image =
object.getString("profile_image_url");
new
DownLoadImageTask(mImageView).execute(Image);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
mTextView.append("Welcome Guest");
Log.e("VOLLEY", "ERROR");
}
})
{ //this is the part, that adds the header to the request
#Override
public Map<String, String> getHeaders() {
Map<String, String> params = new HashMap<String, String>();
params.put("Client-ID", "Client id");
params.put("content-type", "application/json");
return params;
}
};
MySingleton.getInstance(this).addToRequestQueue(jsonObjectRequest);
shoud get twitch user name, description and logo and display to card within the android app. it does, but for the old user entered.
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);
}
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'm new in JSON, but I try to use all answers and didn't work. Help please, what I doing wrong.
protected void onPostExecute(String s) {
super.onPostExecute(s);
progressDialog.dismiss();
editText.setText(s);
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray resultArray = jsonObject.getJSONArray("query");
addresses = new ArrayList<String>();
for (int i = 0; i<resultArray.length(); i++){
addresses.add(resultArray.getJSONObject(i).getString("Name"));
Log.d("DTA",resultArray.getJSONObject(i).getString("Name"));
}
refreshAdapter();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
It's my JSON for parsing.
{
"query":{
"count":2,
"created":"2016-10-04T19:50:08Z",
"lang":"ru",
"results":{
"rate":[
{
"id":"USDRUB",
"Name":"USD/RUB",
"Rate":"62.8240",
"Date":"10/4/2016",
"Time":"7:21pm",
"Ask":"62.8416",
"Bid":"62.8240"
},
{
"id":"EURRUB",
"Name":"EUR/RUB",
"Rate":"70.3460",
"Date":"10/4/2016",
"Time":"7:21pm",
"Ask":"70.3740",
"Bid":"70.3460"
}
]
}
}
}
That's because query is not an array, it is an object. I guess you want to get the objects from rate, this is how to do it:
try {
JSONObject jsonObject = new JSONObject(s);
JSONObject resultsObject = jsonObject.getJSONObject("results");
JSONArray resultArray = resultsObject.getJSONArray("rate");
... etc... now iterate