Send Parameters in Volley Using GSON - java

What I Know
I am able to make a request with the help of JsonObjectRequest using Volley without GSON. Nowadays I am learning of GSON so I can make a request without parameter.
Sample Code
HashMap<String, String> params = new HashMap<String, String>();
params.put("user",userId);
Log.d(TAG + "pp", String.valueOf(params));
String Url = Constants.Base_URL + "getcoupons/";
JsonObjectRequest request = new JsonObjectRequest(Url, new JSONObject(params),
response -> {
Log.d(TAG, "respCoupan" + String.valueOf(response));
try {
String statusResponseObject = response.getString("status");
String msgObject = response.getString("msg");
if (statusResponseObject.equals("200")){
JSONArray jsonArray = response.getJSONArray("response");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject pendingFragResponse = jsonArray.getJSONObject(i);
String codeObject = pendingFragResponse.getString("code");
String typeObject = pendingFragResponse.getString("type");
String amountObject = pendingFragResponse.getString("amount");
String descriptionObject = pendingFragResponse.getString("description");
String leagueObject = pendingFragResponse.getString("league");
String expireObject = pendingFragResponse.getString("expire");
//
couponArrayList.add(new Coupon(codeObject, typeObject, amountObject,
descriptionObject, leagueObject, expireObject));
couponAdapter = new CouponAdapter( couponArrayList, CoupanActivity.this);
recyclerView.setAdapter(couponAdapter);
wp10ProgressBar.hideProgressBar();
wp10ProgressBar.setVisibility(View.GONE);
}
couponAdapter.notifyDataSetChanged();
// wp10ProgressBar.hideProgressBar();
}else {
wp10ProgressBar.hideProgressBar();
wp10ProgressBar.setVisibility(View.GONE);
Toast.makeText(CoupanActivity.this, msgObject, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(this, "Server didn't response, Try after some time", Toast.LENGTH_LONG).show();
}
}, error -> {
error.printStackTrace();
Log.d(TAG + "error", String.valueOf(error.getMessage()));
Toast.makeText(this, "Server didn't response, Try after some time", Toast.LENGTH_LONG).show();
});
MySingleton.getInstance(CoupanActivity.this).addToRequestQueue(request);
JSON
{
"status": "200",
"msg": "Successfully",
"response": [
{
"code": "YUDH20",
"type": "Flat",
"amount": "2",
"description": "Flat 20% credit Discount",
"league": "0",
"league_name": "",
"expire": "2019-08-22"
}
]
}
What I want
I want a clear example to make a request with GSON and Parameter (means send Hashmap values in request with GSON).
Can I use GSON for parameters of a java class?
How can I use GSON for Headers?

you must create data Class "ModelClass" and ResponseClass gson convert your data in "ModelClass" and you can using this class simply:
public class ModelClass {
private String status;
private String msg;
private JSONArray response;
...
}
and create a ResponseClass.class
public class ResponseClass {
private String code;
private String type;
private int amount;
private String description;
private String league;
private String league_name;
private String expire;
...
}
and change your code to:
HashMap<String, String> params = new HashMap<String, String>();
params.put("user", userId);
Log.d(TAG + "pp", String.valueOf(params));
String Url = SyncStateContract.Constants.Base_URL + "getcoupons/";
JsonObjectRequest request = new JsonObjectRequest(Url, new JSONObject(params),
response -> {
Log.d(TAG, "respCoupan" + String.valueOf(response));
try {
Gson gson = new GsonBuilder()
.serializeNulls()
.create();
Type type = new TypeToken<ModelClass>() {
}.getType();
ModelClass result = gson.fromJson(response.toString(), type);
if (result.getMsg().equals("200")) {
for (int i = 0; i < result.getResponse().size(); i++) {
result.getResponse().get(i).getAmount()
result.getResponse().get(i).getCode()
result.getResponse().get(i).getExpire()
...
}}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(this, "Server didn't response, Try after some time", Toast.LENGTH_LONG).show();
}
}, error -> {
error.printStackTrace();
Log.d(TAG + "error", String.valueOf(error.getMessage()));
Toast.makeText(this, "Server didn't response, Try after some time", Toast.LENGTH_LONG).show();
});
MySingleton.getInstance(CoupanActivity.this).addToRequestQueue(request);

Related

TypeToken Object is not displayed correctly in the server

I'm new to TypeTokens and I'm having a problem. I have a shopping cart with products, and
those products I save to Shared Preferences using Typetoken. Because I need to delete and
remove products from recyclerview. Here what I have for adding products:
Gson gson = new Gson();
String json = preferences.getString("artikujtShporta", "");
ArrayList<Artikujt> artikullObject = gson
.fromJson(json, new TypeToken<ArrayList<Artikujt>>(){}.getType());
if (artikullObject != null) {
artikullObject.add(mArtikull);
String jsonString = gson.toJson(artikullObject);
mEditor.putString("artikujtShporta", jsonString);
mEditor.apply();
} else {
ArrayList<Artikujt> arrayArtikuj = new ArrayList<>();
arrayArtikuj.add(mArtikull);
Type listOfTestObject = new TypeToken<ArrayList<Artikujt>>() {}.getType();
String s = gson.toJson(arrayArtikuj, listOfTestObject);
mEditor.putString("artikujtShporta", s);
mEditor.apply();
}
Now I need to send this object to server with some additional information, as below:
private void sendBasketItemsToServer() {
//service where retrofit instance is defined for current route
ProductsService prodService = new ProductsService();
// Retrieve the product of the shopping cart which are saved in shred preferences
SharedPreferences preferences = getSharedPreferences(ITEMS_PREF, Context.MODE_PRIVATE);
SharedPreferences.Editor my_editor = preferences.edit();
String json = preferences.getString("artikujtShporta", "");
Gson gson = new Gson();
ArrayList<Artikujt> artikujt = gson
.fromJson(json, new TypeToken<ArrayList<Artikujt>>(){}.getType());
final int order_number = new Random().nextInt(26) + 75;
String date = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());
// initialize requestBody
RequestBody requestBody = null;
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("klienti", full_name);
jsonObject.put("adresa", fullAddress);
jsonObject.put("produktet", artikujt);
jsonObject.put("date", date);
jsonObject.put("order_number", String.valueOf(order_number));
requestBody = RequestBody.create(String.valueOf(jsonObject),
MediaType.parse("application/json; charset=utf-8"));
System.out.println(jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
// Get token, stored in shared preferences
SharedPreferences editor = Objects.requireNonNull(getApplicationContext())
.getSharedPreferences(TOKEN_PREF, MODE_PRIVATE);
String token = editor.getString("token", "");
Callback<BasketResponse> callback = new Callback<BasketResponse>() {
#Override
public void onResponse(#NotNull Call<BasketResponse> call, Response<BasketResponse> response) {
if (response.isSuccessful()) {
// clear products added to cart
my_editor.clear();
my_editor.apply();
System.out.println(response.body());
Intent intent = new Intent(CheckoutActivity.this, SuccessOrderActivity.class);
startActivity(intent);
}
}
#Override
public void onFailure(#NotNull Call<BasketResponse> call, Throwable t) {
Toast.makeText(CheckoutActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
};
prodService.sendBasketItemsToServer(callback, token, requestBody);
}
All of the items are sent to server and I'm receiving a code 200 as response, but I have a
problem with products, with this line:
jsonObject.put("produktet", artikujt);
is displayed like this:
Is sending the name of the class, not products. When I debug in Android Studio, everything
seems okay
I have two days figuring out how to solve this, but I don't know how. Can someone have any
suggestion what I'm missing here or what I'm doing wrong. Thanks in advance.
Edit: I want to send to server a json like below:
{
"klienti": "my name",
"address": "my address",
"products": [
{
"id": 1,
"price": 2234,
"category": 3,
"created_at": 23-03-2020
},
{
"id": 2,
"price": 2534,
"category": 3,
"created_at": 23-03-2020
}
],
"date": 03-09-2020,
"order_number": 93
}
jsonObject.put("produktet", artikujt);
This line is simply adding the java object to jsonObject.
You can instead do
jsonObject.put("produktet", new Gson().toJson(artikujt));
Edit:
If you are using org.json.JSONObject, try
JSONArray jsonArray = new JSONArray();
artikujt.forEach(item -> {
jsonArray.put(new JSONObject(item));
});
jsonObject.put("produktet", jsonArray);
Though better solution would be to create a java class denoting your target json.
class ArtikujtData {
private String klienti;
private String address;
private List<Artikujt> products;
private String date;
#SerializedName(value = "order_number")
private String orderNumber;
// setters and getters
}
Create object of ArtikujtData and set values to it and use it as
requestBody = RequestBody.create(new Gson().toJson(artikujtData),MediaType.parse("application/json; charset=utf-8"));

JSONArray java.lang.String cannot be converted to JSONObject

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

How can i loop the response of my JSON Object?

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);
}

How to access the json objects using volley

this is the api response i ma accessing the json object and setting the textview of uuid in text view but nothing happen
please suggest code for accessing json object from api response
{
"success":true,
"data {
"serial_key_id":"75",
"order_id":"0",
"product_id":"0",
"serial_key":"WURYFO",
"valid_till":null,
"limit":"0",
"uuid":"",
"used":false
}
}
private void jsonobject() {
String url = "http://mylocalpay.com/?serial_key_api=1&coupon=WURYFO";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i("msg", "response" + response);
try {
JSONObject success = response.getJSONObject("success");
JSONObject data = response.getJSONObject("data");
String serial_key_id = data.getString("serial_key_id");
String order_id = data.getString("order_id");
String product_id = data.getString("product_id");
String serial_key = data.getString("serial_key");
String limit = data.getString("limit");
String uuid = data.getString("uuid");
boolean used = data.getBoolean("used");
JSONObject valid_till = data.getJSONObject("valid_till");
textView.setText(uuid);
System.out.println(serial_key);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
}
});
}
}
You need to parse this JSON into a java object. You could write your own code to do this (which is a very large undertaking) or you could use Googles GSON library.
GSON GitHub page
You can use this library as so
Gson gson = new Gson();
String jsonInString = "{'serial_key_id' : '75'}";
YourClass yourClass = gson.fromJson(jsonInString, YourClass.class);

How to extract the url of an image from a JSON (LastFM API)

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!

Categories

Resources