Writing JSON String as String in Android - android

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"}]

Related

how to get a json property by index

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.

get object integer json to android studio

json with int key value
I've been stuck, to call json like this to android studio using volley, I've never done this before
According to this json with int key value
you are
receiving jsonArray instead of jsonObject
so you have to
send the request of JsonArray with volley
then the request will return jsonArray then you can get your string like this.
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest("url", new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response)
{
try
{
for (int i=0;i<response.length();i++)
{
JSONArray jsonArray = response.getJSONArray(i);
for (int j=0;j<jsonArray.length();j++)
{
String yourString = jsonArray.getString(j);
// you can convert it into int as per your requirement
}
}
} catch (JSONException e)
{
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error)
{
}
});

How do I get JSON array list from the Server?

I am using Volley in my android client to retrieve some JSON values from server.
To get Value I did the following :
#Override
public void onClick(View v) {
queue = Volley.newRequestQueue(MapsActivity.this);
request = new JsonObjectRequest(
Request.Method.GET, // the request method
"http://10.0.2.2:8080/SomeURL",
new JSONObject(map),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response){
textView = (TextView)findViewById(R.id.textView);
textView.setText(response.toString());
}
},
new Response.ErrorListener() { // the error listener
#Override
public void onErrorResponse(VolleyError error) {
textView = (TextView)findViewById(R.id.textView);
textView.setText("Error::"+ error.toString());
Toast.makeText(getApplicationContext(), "Error:" + error.toString(), Toast.LENGTH_LONG).show();
}
});
queue.add(request);
}
});
And In server side I am returning the value as following:
#GET
#Produces("application/json")
public List<Employee> getEmployees() {
EmployeeDAO dao = new EmployeeDAO();
List employees = dao.getEmployees();
return employees;
}
However, I am getting the values in "onErrorResponse()"
You are waiting for a JSONObject in your code, change JsonObjectRequest with JsonArrayrequest. In onResponse(JSONArray response) you parse the response

Android JSON VOlley

Good Day, I would like to get data from this url, and I have problems with onResponse method implementation:
I have something like this:
public void onClick(View v) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "http://horoscope-api.herokuapp.com/",
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
//The Problem is here
JSONArray jsonArray = response.getJSONArray("");
String author = jsonArray.getString(0);
textView.setText(author);
}catch(JSONException e){
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
requestQueue.add(jsonObjectRequest);
}
I don`t understand how to implement onResponse method correctly, I know that I must to get string from array or object, but data from link make me problems to understand what is it object or array, can you write me how to get author field from this url.
Thank you
Since the response in your link is JSONObject, you only need to do the following inside onResponse:
String author = response.getString("author");
textView.setText(author);
Hope this helps!
The response that you are getting is not a JSONArray but is a JSONObject. You could try the below code and see if you are able to get the author.
public void onClick(View v) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "http://horoscope-api.herokuapp.com/",
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String author = response.get("author");
textView.setText(author);
}catch(JSONException e){
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
requestQueue.add(jsonObjectRequest);
}
Hope this helps.
The data from link is JSONObject not JSONArray. Call response.getString("author"); to get author string.
try{
String author = response.getString("author");
} catch(JSONException e) {
e.printStackTrace();
}

Android volley : how to check json type before parsing it

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.

Categories

Resources