in a json file i have several properties, some of them contains one object and some of them are array of objects. the property that contains array of objects is called "products".
but i know the position of that property the i want to parse it is number 3. so to parse the contents of the property that is called "products"
code:
private void fetchPosts2() {
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, API_BASE_URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i(TAG, String.valueOf(response));
String json = null;
JSONObject jresponse = null;
try {
jresponse = response.getJSONObject(3); //the arguments 3 is marked with red it is expected to be a string???
} catch (JSONException e) {
e.printStackTrace();
}
Log.i(TAG, "" + jresponse);//always null
/*String data = "{ ... }";
Object json = new JSONTokener(data).nextValue();
if (json instanceof JSONObject);
else if (json instanceof JSONArray)*/
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(request);
}
You should use JsonArrayRequest instead of JsonObjectRequest to get element with index.
Related
I'm trying to parse json using volley but I cant receive the data. Assume that I received the data. I send that to the recycler view. But I'm not sure about using the JSONObject. Maybe there is a error I couldn't see it. And this is my json website "https://docs.spacexdata.com/#3d6e6f8a-a459-4265-84b1-e2b288a58537".
private void parseJson() {
String url = "https://docs.spacexdata.com/#d65a7f85-e0c7-41ce-b41d-9ad20a238d90";
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for(int i = 0; i < response.length(); i++) {
JSONObject capsuleObject = response.getJSONObject(i);
String details = capsuleObject.getString("details");
String type = capsuleObject.getString("type");
mCapsuleList.add(new Capsule("null", "null", "null", "null", 0, 0, type, details, 0));
}
mCapsuleAdapter = new CapsuleAdapter(CapsuleFragment.this.getContext(), mCapsuleList);
mRecyclerView.setAdapter(mCapsuleAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mRequestQueue.add(request);
}
There is a lot of value in json but I just want to receive "type" and "detail". It says my request is null. So how can i parse this?
Below is the response what i am getting i want to get the data from "SourceJson" m not ble to understnd why i am getting "" in source json please help me
{
"incomingOrder": [
{
"Namw": 8510,
"Surname": "00",
"mob": "00",
"phone": "000",
"SourceJson": "{\"cart_gst\":30.21,\"instructions\":\"\",\"order_packing_charges\":30,\"cart_igst_percent\":0,\"cart_sgst\":15.1038,}",
"test": "NotSynced",
"test": "DPA",
}]}
Try this code :
requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest obreq = new JsonObjectRequest(Request.Method.GET, JsonURL,
// The third parameter Listener overrides the method onResponse() and passes
//JSONObject as a parameter
new Response.Listener<JSONObject>() {
// Takes the response from the JSON request
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("incomingOrder");
JSONObject jsonObject = jsonArray.getJSONObject(0);
JSONObject objSourceJson=jsonObject.getJSONObject("SourceJson");
Log.i("IvaSourceJson",objSourceJson.toString());
String cart_gst=objSourceJson.getString("cart_gst");
String instructions=objSourceJson.getString("instructions");
}
// Try and catch are included to handle any errors due to JSON
catch (JSONException e) {
// If an error occurs, this prints the error to the log
e.printStackTrace();
}
}
},
// The final parameter overrides the method onErrorResponse() and passes VolleyError
//as a parameter
new Response.ErrorListener() {
#Override
// Handles errors that occur due to Volley
public void onErrorResponse(VolleyError error) {
Log.e("Volley", "Error");
}
}
);
// Adds the JSON object request "obreq" to the request queue
requestQueue.add(obreq);
As it is JSONArray data is of list type, better not to use jsonArray.getJSONObject(0);.
Use this code for multiple results,
StringRequest request = new StringRequest(Request.Method.GET, "", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Response", response);
try {
JSONObject object = new JSONObject(response);
JSONArray array = object.getJSONArray("incomingOrder");
for (int i = 0; i < array.length(); i++){
JSONObject object1 = array.getJSONObject(i);
String name = object1.getString("Namw");
String surname = object1.getString("Surname");
String mob = object1.getString("mob");
String phone = object1.getString("phone");
String sourceJson = object1.getString("SourceJson");
String test = object1.getString("test");
String test1 = object1.getString("test");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error", error.getMessage());
}
});
Context context;
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
queue.add(request);
Code this in any method and call the method where the action needed.
I am creating an app which uses volley. I used JsonObjectRequest() to send Json object through volley. Thus I had to create Jason Object from values taken from Edit text.
btn_enter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SN1 = inputsn.getText().toString();
Name1 = inputname.getText().toString();
}
});
JSONObject jsonMenu= null;
try {
jsonMenu = new JSONObject("");//string is to be added here
Toast.makeText(Add.this,"Made Obj",Toast.LENGTH_SHORT);
} catch (JSONException e) {
e.printStackTrace();
Log.d("Add","Error");
}
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, URL,jsonMenu, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("MainActivity",response.toString());
Toast.makeText(Add.this,"Response Received",Toast.LENGTH_SHORT);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Add.this,"Error",Toast.LENGTH_SHORT);
}
});
RequestQueue queue= Volley.newRequestQueue(this);
queue.add(request);
Here, [{"SN":1,"Name":"Ajeeb"}] values 1 and Ajeeb is to be replaced by values of SN1 and Name1 respectively.Such that I can add it to Java code
JSONObject jsonMenu = new JSONObject("\\String goes here");
You can create property for json object and than as it to your Json Object
jsonMenu.addProperty("SN", SN1);
jsonMenu.addProperty("Name", Name);
This will result in {"SN":1,"Name":"Ajeeb"}
And if you want to create an array for it
JSONArray jsonArray = new JSONArray();
jsonArray.put(jsonMenu);
This will result in [{"SN":1,"Name":"Ajeeb"}]
I'm trying to get the data from the json file from reddit (https://www.reddit.com/r/gifs/.json). But I keep getting the same error:
org.json.JSONException: No value for children
this is my code:
RequestQueue queue = Volley.newRequestQueue(this);
String url ="https://www.reddit.com/r/funny.json";
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray children = response.getJSONArray("children");
} catch (JSONException e) {
e.printStackTrace();
Log.i(TAG, "ERROR !!!!" + e);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i(TAG, "ERROR");
}
});
queue.add(jsObjRequest);
If someone can help me it would be nice!
You should do like this as children is child of data object
JsonObject data = response.getJsonObject("data");
JsonArray children = data.getJsonArray("children");
Do this as your children Array is inside your data object
JSONObject data = response.getJSONObject("data");
JSONArray children = data.getJSONArray("children");
Is it possible to check the type of json beforehand? I'm somteimes getting an array and sometimes an object and I don't see how to handle these 2 cases without doing 2 different functions...
public void RequestApi( String url, final ApiResponse<ApiResult> completion )
{
Log.v("Performing request: ", url);
JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.GET, hostname+url, (JSONObject) null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response)
{
Log.v("RequestApi Response", response.toString());
//Log.v("Data: ", response.toString());
try {
ApiResult res = new ApiResult();
Boolean success = response.getBoolean("success");
//here need to check type, sometimes array, sometimes object
JSONArray data = response.getJSONArray("data");
res.success = success;
res.data = data;
completion.onCompletion(res);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
ApiResult res = new ApiResult();
res.success = false;
completion.onCompletion(res);
}
}
);
AppController.getInstance().addToRequestQueue(jsonRequest);
}
Use StringRequest
// 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) {
Object json = new JSONTokener(response).nextValue();
if (json instanceof JSONObject)
//you have an object
else if (json instanceof JSONArray)
//you have an array
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO something
}
});
Most simple solution - look at first string character. If it is { - object, if [ - array. But I think better to do following:
try {
JSONObject object = new JSONObject(value);
}
catch (JSONException) {
//if it throws, "value" contains not a JSONObject
JSONArray array = new JSONArray(value);
}
After going through the API I found a simple solution.
Since you are not sure of the return type, follow mentioned below steps.
First:
JSONArray arrayInstance = new JSONArray();// declare array instance to handle both the cases
Object objectInstance = rootObject.get(key); //key is the response string holding the value either jsonArray or jsonObject
Second:
if(objectInstance instanceof JSONArray){
arrayInstance = rootObject.getJSONArray(key);
}
else{
JSONObject tempObject = rootObject.getJSONObject(key);
arrayInstance.put(tempObject);
}
Third:
You can iterate though the array for the desired processing.