Getting Simple Json Object Response Using Retrofit Library

Getting simple JSON object response using Retrofit library

Instead of Callback with JSONObject class, you could use the Retrofit basic callback which use the Response class and then, once you get the response, you had to create the JSONObject from it.

See this:
https://stackoverflow.com/a/30870326/2037304

Otherwise you can create your own model class to handle the response.

First the Result class:

public class Result {
public int id;
public String name;
public String email;
public String password;
public boolean status;
public Date created;
}

And then your response class to use with Retrofit

public class MyResponse {
public boolean status;
public Result result;
public String message;
}

Now you can call:

 @GET("/stockers/login") 
public void login(
@Query("email") String email,
@Query("password") String password,
Callback<MyResponse> callback);

How to get JSON object using Retrofit?

Your interface should look like this :

public interface RetrofitInterface {
@GET("ALE2")
Call<ResponseBody> getData();
}

To get raw json object return type should be Call<ResponseBody>
Once that is done in response you can handle it like below :

retrofit.create(RetrofitInterface.class).getData().enqueue(new Callback<ResponseBody> () {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
String responseBody = response.body().string();
JSONObject json = new JSONObject(responseBody);
}

@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {

}
});

This is how you can set string in JSON object.

get simple json object using retrofit 2

After lots of R&D I got answer. Please find it below

Use JsonObject from package com.google.gson instead of JSONObject from package org.json

After that call Call<JsonObject> result() and in onResponse (Response<JsonObject> response) method used to call response.body() or response.body().toString(); it wil print correct Json from apiwhatever you want

Android - Simple JSON object response using Retrofit 2.1.0?

Use body() method to get your response model. In your case you have incorrect model in request though. In your case the response is an array for some reason. And the parent object is JsonSignIn. So you need to update your code accordingly.

public interface Interface_SignIn {
@GET("/GiveData.svc/login/{UserName}/{Password}")
Call<List<JsonSignIn>> getJSONSignIn(@Path("UserName") String UserName,
@Path("Password") String Password);
}

Don't forget to update your request.

Call<List<JsonSignIn>> call = request.getJSONSignIn(username, password);
call.enqueue(new Callback<List<JsonSignIn>>() {
@Override
public void onResponse(Call<ModelSignIn> call, Response<List<JsonSignIn>> response) {
List<JsonSignIn> JSI = response.body();

}

@Override
public void onFailure(Call<List<JsonSignIn>> call, Throwable t) {

}
});

Retrofit 2: Get JSON from Response body

Use this link to convert your JSON into POJO with select options as selected in image below

Sample Image

You will get a POJO class for your response like this

public class Result {

@SerializedName("id")
@Expose
private Integer id;
@SerializedName("Username")
@Expose
private String username;
@SerializedName("Level")
@Expose
private String level;

/**
*
* @return
* The id
*/
public Integer getId() {
return id;
}

/**
*
* @param id
* The id
*/
public void setId(Integer id) {
this.id = id;
}

/**
*
* @return
* The username
*/
public String getUsername() {
return username;
}

/**
*
* @param username
* The Username
*/
public void setUsername(String username) {
this.username = username;
}

/**
*
* @return
* The level
*/
public String getLevel() {
return level;
}

/**
*
* @param level
* The Level
*/
public void setLevel(String level) {
this.level = level;
}

}

and use interface like this:

@FormUrlEncoded
@POST("/api/level")
Call<Result> checkLevel(@Field("id") int id);

and call like this:

Call<Result> call = api.checkLevel(1);
call.enqueue(new Callback<Result>() {
@Override
public void onResponse(Call<Result> call, Response<Result> response) {
if(response.isSuccessful()){
response.body(); // have your all data
int id =response.body().getId();
String userName = response.body().getUsername();
String level = response.body().getLevel();
}else Toast.makeText(context,response.errorBody().string(),Toast.LENGTH_SHORT).show(); // this will tell you why your api doesnt work most of time

}

@Override
public void onFailure(Call<Result> call, Throwable t) {
Toast.makeText(context,t.toString(),Toast.LENGTH_SHORT).show(); // ALL NETWORK ERROR HERE

}
});

and use dependencies in Gradle

compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.+'

NOTE: The error occurs because you changed your JSON into POJO (by use of addConverterFactory(GsonConverterFactory.create()) in retrofit). If you want response in JSON then remove the addConverterFactory(GsonConverterFactory.create()) from Retrofit. If not then use the above solution

JSON Response Using Retrofit on Android

I appreciate all answers, thanks to everyone. I managed to solve the problem by putting pieces together since Retrofit has poor documentation, and some answers aren't detailed enough to be accepted. I wanted to extract data from JSON response from this link: https://api.spotify.com/v1/search?q=Beyonce&type=artist

Step1:
Create a Pojo class to deserialize the items in the response. deserializing basically means that in this JSON response, we have "artists" array and inside it "href" string and "items" list, so as Aritra suggested, we can use http://www.jsonschema2pojo.org to generate the pojo classes that will deserialize these items for us. Here how mine look like after some modification:

public class Data implements Serializable{

@SerializedName("artists")
Artists artists;

public Artists getArtists() {
return artists;
}


public static class Artists {

@SerializedName("href")
private String href;

@SerializedName("items")
private List<Item> items;


public String getHref(){
return href;
}

public List<Item> getItems(){
return items;
}

}// Artists



public static class Item {
// You have your item class here
@SerializedName("external_urls")
@Expose
private ExternalUrls externalUrls;
@SerializedName("followers")
@Expose
private Followers followers;
@SerializedName("genres")
@Expose
private List<Object> genres = new ArrayList<Object>();
@SerializedName("href")
@Expose
private String href;
@SerializedName("id")
@Expose
private String id;
@SerializedName("images")
@Expose
private List<Object> images = new ArrayList<Object>();
@SerializedName("name")
@Expose
private String name;
@SerializedName("popularity")
@Expose
private Integer popularity;
@SerializedName("type")
@Expose
private String type;
@SerializedName("uri")
@Expose
private String uri;


public Item() {
name = "";
id = "";
images = new ArrayList<>();
}


/**
* @return The externalUrls
*/
public ExternalUrls getExternalUrls() {
return externalUrls;
}

/**
* @param externalUrls The external_urls
*/
public void setExternalUrls(ExternalUrls externalUrls) {
this.externalUrls = externalUrls;
}

/**
* @return The followers
*/
public Followers getFollowers() {
return followers;
}

/**
* @param followers The followers
*/
public void setFollowers(Followers followers) {
this.followers = followers;
}

/**
* @return The genres
*/
public List<Object> getGenres() {
return genres;
}

/**
* @param genres The genres
*/
public void setGenres(List<Object> genres) {
this.genres = genres;
}

/**
* @return The href
*/
public String getHref() {
return href;
}

/**
* @param href The href
*/
public void setHref(String href) {
this.href = href;
}

/**
* @return The id
*/
public String getId() {
return id;
}

/**
* @param id The id
*/
public void setId(String id) {
this.id = id;
}

/**
* @return The images
*/
public List<Object> getImages() {
return images;
}

/**
* @param images The images
*/
public void setImages(List<Object> images) {
this.images = images;
}

/**
* @return The name
*/
public String getName() {
return name;
}

/**
* @param name The name
*/
public void setName(String name) {
this.name = name;
}

/**
* @return The popularity
*/
public Integer getPopularity() {
return popularity;
}

/**
* @param popularity The popularity
*/
public void setPopularity(Integer popularity) {
this.popularity = popularity;
}

/**
* @return The type
*/
public String getType() {
return type;
}

/**
* @param type The type
*/
public void setType(String type) {
this.type = type;
}

/**
* @return The uri
*/
public String getUri() {
return uri;
}

/**
* @param uri The uri
*/
public void setUri(String uri) {
this.uri = uri;
}

}// Item

}

So, the array "artists" represented as Artists class that contains href String and items list elements all serialized to match the JSON response. The items list is of type Item class, which contains many serialized elements, like id, name, images.. etc. all serialized to mach the JSON response.

Step2:
The url is divided into 2 parts, a base and an endpoint. We use the base when we create Retrofit2 request. I'm calling this request from onCreate method:

private void loadJSON() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.spotify.com")
.addConverterFactory(GsonConverterFactory.create())
.build();
final Artists_Interface request = retrofit.create(Artists_Interface.class);

Call<Data> call = request.getArtists();
call.enqueue(new Callback<Data>() {
@Override
public void onResponse(Call<Data> call, Response<Data> response) {

if (response.isSuccessful()) {

System.out.println(" Href ::::. : " + response.body().getArtists().getHref());

List<Data.Item> items = response.body().getArtists().getItems();
for (int i = 0; i < items.size(); i++) {
adapter.addArtist(items.get(i));
}
}
else { System.out.println(" :::. NO RESPONSE .::: "); }

}// End onResponse

@Override
public void onFailure(Call<Data> call, Throwable t) {
System.out.println("onFAIL::: " + t);
}
});

Then, we use the endpoint in the Retrofit2 interface class:

public interface Artists_Interface {

@GET("/v1/search?q=Beyonce&type=artist")
Call<Data> getArtists();

}

Step3:
Just assign the values we got from the response to the elements in our views. In step two I assigned the items list to the my recyclerView adapter, so here how my adapter look like:

public class Artists_Adapter extends RecyclerView.Adapter<Artists_Adapter.ViewHolder> {

private ArrayList<Data.Item> artists;

public Artists_Adapter(ArrayList<Data.Item> artists) {
this.artists = artists;
}

@Override
public Artists_Adapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_artists, viewGroup, false);
return new ViewHolder(view);
}

@Override
public void onBindViewHolder(Artists_Adapter.ViewHolder viewHolder, int i) {

viewHolder.name.setText(artists.get(i).getName());

}

@Override
public int getItemCount() {
if(artists == null){
return 0;
}
else {
return artists.size();
}
}

public void addArtist(Data.Item item){

artists.add(item);

}

public class ViewHolder extends RecyclerView.ViewHolder{
private TextView name ;
private ImageView imageView;
public ViewHolder(View view) {
super(view);

name = (TextView)view.findViewById(R.id.name);
imageView = (ImageView) view.findViewById(R.id.image);

}
}

}

And here how my onCreate() method look like:

    private RecyclerView recyclerView;
private ArrayList<Data.Item> data = new ArrayList<>();
private Artists_Adapter adapter;
static Context ctx;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);

ctx = this;
url = "https://api.spotify.com/v1/search?q=Beyonce&type=artist";

loadJSON();
initViews();


}// onCreate


private void initViews() {
recyclerView = (RecyclerView) findViewById(R.id.card_recycler_view);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
adapter = new Artists_Adapter(data);
recyclerView.setAdapter(adapter);

}

Parse JSON array response using Retrofit & Gson

Please try to use this one

    @FormUrlEncoded
@POST("api/sponsors")
Call<List<SponsorsResult>> getStatesAndDistrict(
@Field("xyz") String field1
);



Call <List<SponsorsResult>> call = service.getSponsorsValue();

call.enqueue(new Callback<List<SponsorsResult>>() {
@Override
public void onResponse(Call<List<SponsorsResult>> call, Response<List<SponsorsResult>> response) {

List<SponsorsResult> rs = response.body();

}

@Override
public void onFailure(Call<List<SponsorsResult>> call, Throwable t) {

}
});



class SponsorsResult {

@SerializedName("sponsors")
private List<SponsorsValue> sponsors;

public List<SponsorsValue> getSponsors() {
return sponsors;
}
}

class SponsorsValue{
@SerializedName("leg_id")
@Expose
private String legId;
@SerializedName("type")
@Expose
private String type;
@SerializedName("name")
@Expose
private String name;

public String getLegId() {
return legId;
}

public void setLegId(String legId) {
this.legId = legId;
}

public String getType() {
return type;
}

public void setType(String type) {
this.type = type;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

}

Please let me know if you are facing any issue.

json response iteration android studio/retrofit

In your provided JSON hierarchy photo the name of the root element doesn't appear, so I assumed it as "root_element" in below script

  • Here the entire JSON response can be read as a JSONObject.
  • And as this JSONObject has multiple elements in it (in picture
    named as 0, 1, 2..); then you can get a JSONArray using
    getJSONArray() method.
  • Then you can loop through this JSONArray to get a paricular element from the (0, 1, 2...)
  • After that you can another JSONObject from this particular element which is owner in your JSON structure photo.
  • And finally you can read Strings of this owner using getString()
String jsonResponse = ""; // Put the entire JSON response as a String 
JSONObject root = new JSONObject(jsonResponse); // jsonResponse is the entire JSON string
JSONArray rootArray = root.getJSONArray("root_element"); // your root element is not show in your provided photo

for (int i = 0; i < rootArray.length(); i++) {

JSONObject element = rootArray.getJSONObject(i);
JSONObject owner = element.getJSONObject("owner");
String email = owner.getString("email");
String givenName = owner.getString("givenName");
String id = owner.getString("id");
String lastName = owner.getString("lastName");
String realm = owner.getString("realm");
String userName = owner.getString("userName");

}

How to parse Json response in android from retrofit

Parse json like below:

// ResponseObject is your root object
public class ResponseObject{

@SerializedName("payload")
private Payload payload;

public Payload getPayload() {
return payload;
}
}
class Payload{
@SerializedName("authenticated")
private boolean isAuthenticated;

@SerializedName("inmate_details")
private InMateObject inMateObject;

@SerializedName("order_id")
private String orderId;

@SerializedName("order_detail")
private List<Order> orderList;

// Make sure to get String value as response for "transaction_history" key
@SerializedName("transaction_history")
private String transactionDetails;

public InMateObject getInMateObject() {
return inMateObject;
}
}
class InMateObject{
@SerializedName("jail_alt_id")
private String jainAltId;
@SerializedName("facility_number")
private String facilityNumber;
@SerializedName("last_name")
private String lastName;
@SerializedName("first_name")
private String firstName;
@SerializedName("dob")
private String dob;
@SerializedName("middle_name")
private String middleName;
@SerializedName("sex")
private String sex;
// Add other fields like wise.

}
class Order{
@SerializedName("id") // If id is Integer in json then use int type
private String id;
@SerializedName("order_id")
private String orderId;
@SerializedName("product_code")
private String productCode;
@SerializedName("quantity")
private int quantity;
}

And then your Api call would look like below:

         call.enqueue(new Callback<ResponseObject>() {
@Override
public void onResponse(Call<ResponseObject> call, Response<ResponseObject> response) {
System.out.println(response);
if (response.isSuccessful()){
//Inmate_details balance = response.body().getInmate_details();
// Basically you are getting ResponseObject as response. So, collect payload first from it. And then collect inmate_details from Payload.
Payload payload = response.body().getPayload();
InMateObject inMateObject = payload.getInMateObject();
pDialog.dismissWithAnimation();
Toasty.success(LoginActivity.this, "Success! Redirecting To Home", Toast.LENGTH_SHORT, true).show();
startActivity(new Intent(LoginActivity.this,PDFActivity.class));
}
}
}


Related Topics



Leave a reply



Submit