My JSON like this:-
{
"status": "approved",
"work_flow": {
"id": 27,
"name": "xgfdhx",
"role": "xfhxfhg",
"user_image": null
}
}
And my GsonCode is this:-
EmployeeDTO eDTO = gson.fromJson(json, eDTO.class);
so
Log.d(TAG,"Response: "+eDTO.getStatus())-----o/p:- Approved
means I am successfully get the status but I had problem to iterate the inner JSON,
Can someone explain me or help me how to get the work_flow inner JSON data.
using GSON builder?
Try
1. Change this line EmployeeDTO eDTO = gson.fromJson(json, eDTO.class); to
EmployeeDTO eDTO = gson.fromJson(json, EmployeeDTO.class);
2. Add class EmployeeDTO.java
public class EmployeeDTO {
String status;
#SerializedName("work_flow")
WorkFlow workFlow;
}
3. Add class WorkFlow.java
public class WorkFlow {
int id;
String name;
String role;
String userImage;
}
Related
I have a Json like this
"data": {
"2020-05-01": {
"tanggal": "Jumat, 01\/05\/2020",
"subuh": "05:05",
"dzuhur": "12:33",
"ashar": "15:51",
"maghrib": "18:40",
"isya": "19:51"
},
"2020-05-02": {
"tanggal": "Sabtu, 02\/05\/2020",
"subuh": "05:04",
"dzuhur": "12:33",
"ashar": "15:51",
"maghrib": "18:40",
"isya": "19:52"
}
}
how can I get the Json, If the object is Date but I must have to use retrofit
Thanks for your help.
Try to use a Map:
class Data {
Map<String, MyObject> firstData;
Map<String, MyObject> secondData;
}
Where MyObject is:
class MyObject {
String tanggal;
String subuh;
String dzuhur;
String ashar;
String maghrib;
String isya;
}
I'm trying to parse a JSON object using retrofit 2.0 following this guide, but it doesn't work. I think it's because of a difference in JSON format.
Here is a nested JSON object with the format:
{
"SearchService": {
"list_total_count": 531,
"RESULT": {
"CODE": "INFO-001",
"MESSAGE": "SUCCESS"
},
"row": [{
"ID": "1983",
"NAME": "SAN",
"NUM": "38",
}, {
"ID": "1984",
"NAME": "DU",
"NUM": "27",
}]
}
}
Here is class code using SerializedName:
RowList.java
public class RowList {
#SerializedName("row")
#Expose
private ArrayList<Row> rows= new ArrayList<>();
public ArrayList<Row> getRows() {
return rows;
}
public void setRows(ArrayList<Row> rows) {
this.rows= rows;
}
}
Row.java
public class Row{
#SerializedName("ID")
#Expose
private String id;
#SerializedName("NAME")
#Expose
private String name;
#SerializedName("NUM")
#Expose
private String num;
/*getter setter*/
}
Read that guide.
There are two approaches to create Model class. The first way is the manual approach, which requires you to learn how to use the Gson library. The second approach is you can also auto-generate the Java classes you need by capturing the JSON output and using jsonschema2pojo
Looks like you've attempted approach one, but haven't (yet?) tried reading over the Gson documentation.
Okay, you have a Row. That covers the objects within "row": [...], so you also need objects for the following:
"SearchService": {}
"RESULT": {}
I don't think the RowList class is necessary. List<Row> is fine.
For example,
class Result {
#SerializedName("CODE")
String code;
#SerializedName("MESSAGE")
String message;
}
class SearchService {
#SerializedName("list_total_count")
long count;
#SerializedName("RESULT")
Result result;
#SerializedName("row")
private ArrayList<Row> rows= new ArrayList<>();
}
(removed #Expose for conciseness)
Then, Retrofit would use Call<SearchService>
I'm a newbie in Retrofit. How to parse the Json below using retrofit?
{
"data": {
"Aatrox": {
"id": 266,
"title": "a Espada Darkin",
"name": "Aatrox",
"key": "Aatrox"
},
"Thresh": {
"id": 412,
"title": "o Guardião das Correntes",
"name": "Thresh",
"key": "Thresh"
}
},
"type":"champion",
"version":"6.23.1"
}
You could make your model POJO contain a Map<String, Champion> to deserialize into, to deal with the dynamic keys.
Example:
public class ChampionData {
public Map<String, Champion> data;
public String type;
public String version;
}
public class Champion {
public int id;
public String title;
public String name;
public String key;
}
I'm not familiar with Retrofit besides that, but as someone in the comments said, the deserializing is done by Gson:
public ChampionData champions = new Gson().fromJson(json, ChampionData.class);
So to build on to the answer someone else posted, you can then do the following, assuming you've added the GsonConverterFactory:
public interface API {
#GET("path/to/endpoint")
Call<ChampionData> getChampionData();
}
Assuming Retrofit2, the first thing you need to do is call following when building your Retrofit instance.
addConverterFactory(GsonConverterFactory.create())
Then it's just a matter of writing a POJO (e.g. MyPojoClass) that maps to the json and then adding something like following to your Retrofit interface.
Call<MyPojoClass> makeRequest(<some params>);
This is how my JSON response looks
[
{
"id": 1,
"PhName": "sample string 2",
"Longitude": 3.1,
"Latitude": 4.1,
"ApplicationUserId": "sample string 5"
},
{
"id": 1,
"PhName": "sample string 2",
"Longitude": 3.1,
"Latitude": 4.1,
"ApplicationUserId": "sample string 5"
}
]
this is my retrofit interface call
#GET("/api/GPS")
#Headers({
"Accept: application/json"
})
Call<List<UserResponse>> search(#Query("search") String search,
#Header("Authorization") String auth);
Pojo Class
public class UserResponse {
#SerializedName("Id")
int id;
#SerializedName("UserName")
String phName;
#SerializedName("Longitude")
int lon;
#SerializedName("Latitude")
int lat;
#SerializedName("ApplicationUserId")
String appUserId;
//getters and setters
}
Retrofit declaration
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(PerformLogin.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
Getting data and using it
MyApiEndpointInterface apiService =
retrofit.create(MyApiEndpointInterface.class);
Call<List<UserResponse>> call = apiService.search(query,"Bearer "+token);
call.enqueue(new Callback<List<UserResponse>>() {
#Override
public void onResponse(Call<List<UserResponse>> call, Response<List<UserResponse>> response) {
List<UserResponse> userList = response.body();
Log.w("My App", response.message());
for (int i = 0; i <userList.size() ; i++) {
Log.w("My App", userList.get(i).getPhName()+""+i);
}
//mAdapter = new MyAdapter(getContext(),userList);
//mRecyclerView.setAdapter(mAdapter);
}
#Override
public void onFailure(Call<List<UserResponse>> call, Throwable t) {
Log.w("My App", t.getMessage());
}
});
my response
W/My App: OK
W/My App: null 0
W/My App: null 1
W/My App: null 2
W/My App: null 3
In this case I am suppose to receive four result from the search and the names are giving me null.
Is there anything I am doing wrong or a better solution to this?
You are using wrong serialize name. You are trying to assign value from node UserName to phName, which is not available. So, you are getting null.
Change
#SerializedName("UserName")
String phName;
with
#SerializedName("PhName") // change this
String phName;
Also, #SerializedName("Id") should be #SerializedName("id"). It's case sensitive.
Your SerializedName fields and the JSON fields don't match.
JSON: id -> GSON: Id
JSON: PhName -> GSON: UserName
Those two don't add up. You have to alter your annotations accordingly:
#SerializedName("id")
int id;
#SerializedName("PhName")
String phName;
How to read a JSONArray from a JSONObject using GSON.
I am trying to read this JSON String:
String str = { "text" : [
{
"id": 1,
"msg":"abc"
},
{
"id": 2,
"msg":"xyz"
},
{
"id": 3,
"msg":"pqr"
}
] }
The class is:
Class A {
int id;
String msg;
// And setters and getters
}
This code does not work:
class Test {
A [] text;
}
Test t = gson.fromJson(response, Test.class);
Also
class Test {
ArrayList<A> text = new ArrayList<A>();
}
Test t = gson.fromJson(response, Test.class);
How else can i read the string using my Test class?
Please help...
Update your class
public class A {
#SerializedName("id")
int id;
#SerializedName("msg")
String msg;
// And All setter and getter
}
The values given as "JSON String" are values to initiate the A class. And they are an array of As. What might work is
A[] t = gson.fromJson(response, A[].class);
Deserializing arrays is described in the manual, 5.4 Array Examples.