Map multi-level json string into class object in java - java

I have following JSON structure:
{
"result": {
"category": [{
"id": "3",
"name": "category name",
"slug": "sllug",
"image": "imageurl",
"sub-categories": [{
"id": "3",
"name": "category name",
"slug": "sllug",
"image": "imageurl",
"sub-categories": [{
"id": "3",
"name": "category name",
"slug": "sllug",
"image": "imageurl",
"sub-categories": []
}]
}]
},
{
"id": "3",
"name": "category name",
"slug": "sllug",
"image": "imageurl",
"sub-categories": []
}
]
}
}
I need to create class with the above JSON.
I have created two classes as HomeCategoryModel and HomeSubCategoryModel.
There may be multiple sub-categories in each level.
How to map this type of json into classes.
HomeCategoryModel class:
public class HomeCategoryModel {
public int Id;
public String Name;
public String Slug;
public String ImageUrl;
public ArrayList<HomeSubCategoryModel> SubCategories;
//...
//getter, setter
}
HomeSubCategory class:
public class HomeSubCategoryModel {
public int Id;
public String Name;
public String Slug;
public String ImageUrl;
public ArrayList<HomeSubCategoryModel> SubCategories;
//getter setter
}
I have tried to parse using recursive function like this but doesn't seem to work:
JSONObject allLists = jsonObject.getJSONObject("result");
JSONArray catArray = allLists.getJSONArray("category");
ArrayList<HomeCategoryModel> categoryList = new ArrayList<HomeCategoryModel>();
for (int i = 0; i < catArray.length(); i++) {
JSONObject jObj = catArray.getJSONObject(i);
HomeCategoryModel categoryModel = new HomeCategoryModel();
categoryModel.setId(Integer.parseInt(jObj.getString("id")));
categoryModel.setName(jObj.getString("name"));
categoryModel.setSlug(jObj.getString("slug"));
categoryModel.setImageUrl(jObj.getString("image"));
JSONArray productsArray = jObj.getJSONArray("sub-categories");
if (productsArray.length() > 0) {
parseSubCategories(productsArray);
}
categoryList.add(categoryModel);
}
And:
public static ArrayList<HomeSubCategoryModel> parseSubCategories(JSONArray arr) {
ArrayList<HomeSubCategoryModel> subLists = new ArrayList<HomeSubCategoryModel>();
for (int i = 0; i < arr.length(); i++) {
try {
JSONObject childObj = arr.getJSONObject(i);
HomeSubCategoryModel categoryModel = new HomeSubCategoryModel();
categoryModel.setId(Integer.parseInt(childObj.getString("id")));
categoryModel.setName(childObj.getString("name"));
categoryModel.setSlug(childObj.getString("slug"));
categoryModel.setImageUrl(childObj.getString("image"));
JSONArray subArray = childObj.getJSONArray("sub-categories");
if (subArray.length() > 0) {
parseSubCategories(subArray);
}
subLists.add(categoryModel);
} catch (JSONException e) {
e.printStackTrace();
}
}
return subLists;
}
Please suggest me. Thank you.

if you would like to use Gson then i can suggest something like below.
Generate your POJO like this
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("result")
#Expose
private Result result;
public Result getResult() {
return result;
}
public void setResult(Result result) {
this.result = result;
}
public class Result {
#SerializedName("category")
#Expose
private List < Category > category = null;
public List < Category > getCategory() {
return category;
}
public void setCategory(List < Category > category) {
this.category = category;
}
}
public class Category {
#SerializedName("id")
#Expose
private String id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("slug")
#Expose
private String slug;
#SerializedName("image")
#Expose
private String image;
#SerializedName("sub-categories")
#Expose
private List < SubCategory > subCategories = null;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSlug() {
return slug;
}
public void setSlug(String slug) {
this.slug = slug;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public List < SubCategory > getSubCategories() {
return subCategories;
}
public void setSubCategories(List < SubCategory > subCategories) {
this.subCategories = subCategories;
}
}
public class SubCategory_ {
#SerializedName("id")
#Expose
private String id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("slug")
#Expose
private String slug;
#SerializedName("image")
#Expose
private String image;
#SerializedName("sub-categories")
#Expose
private List < Object > subCategories = null;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSlug() {
return slug;
}
public void setSlug(String slug) {
this.slug = slug;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public List < Object > getSubCategories() {
return subCategories;
}
public void setSubCategories(List < Object > subCategories) {
this.subCategories = subCategories;
}
}
}
and then
Gson gson = new Gson();
Example exp = gson.fromJson("your json string",Example.class);
And you are done.

Related

JsonArray field in a JsonObject to Java Object

Below is my JSON data. I want to convert this to POJOs to store the Name,id,profession in a header table and the respective Jsonarray field in a child table.
JSON:
{
"Name": "Bob",
"id": 453345,
"Profession": "Clerk",
"Orders": [
{
"Item": "Milk",
"Qty": 3
},
{
"Item": "Bread",
"Qty": 3
}
]
}
Entity classes:
public class User {
private String name;
private Integer id;
private String Profession;
private JsonArray Orders;
private UserCart userCart;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getProfession() {
return Profession;
}
public void setProfession(String profession) {
Profession = profession;
}
public JsonArray getOrders() {
return Orders;
}
public void setOrders(JsonArray orders) {
Orders = orders;
}
public UserCart getUserCart() {
return userCart;
}
public void setUserCart(UserCart userCart) {
this.userCart = userCart;
}
}
public class UserCart {
private String item;
private Integer qty;
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public Integer getQty() {
return qty;
}
public void setQty(Integer qty) {
this.qty = qty;
}
}
But when I do below; I get error
Cannot deserialize instance of org.json.JSONArray out of START_ARRAY
token
User user = new User();
JsonNode data = new ObjectMapper().readTree(jsonString);
user = headerMap.readValue(data.toString(), User.class);
How do I go about assigning the entire JSON to both the Java objects ?
Use List<UserCart> for array data in json and use #JsonProperty for mapping different json node name to java object field. No need to use extra field (JsonArray Orders) anymore.
#JsonProperty("Orders")
private List<UserCart> userCart;

Modules list is not coming after parsing json

Hi in the below code modules list is not coming after parsing the json and i have created different pojo classes for different classes and i am not getting the expected json response from server.
Can any one tell me where i did the mistake for json parsing and complete json is not coming as json
Activity.java:
final String username = username1.getText().toString();
final String password = password1.getText().toString();
String operation = "loginAndFetchModules";
final GetNoticeDataService service = RetrofitInstance.getRetrofitInstance().create(GetNoticeDataService.class);
/** Call the method with parameter in the interface to get the notice data*/
Call<LoginAndFetchModules> call1 = service.GetLoginModuleList(operation, username, password);
/**Log the URL called*/
Log.wtf("URL Called", call1.request().url() + "");
call1.enqueue(new Callback<LoginAndFetchModules>() {
#Override
public void onResponse(Call<LoginAndFetchModules> call1, Response<LoginAndFetchModules> response) {
Log.e("response",new Gson().toJson(response.body()));
if (response.isSuccessful()) {
Log.e("response",new Gson().toJson(response.body()));
LoginAndFetchModules loginAndFetchModules = response.body();
String success = loginAndFetchModules.getSuccess();
if (success.equals("true")) {
ArrayList<String> modules = new ArrayList<String>();
try {
JSONArray jsonArray = new JSONArray(loginAndFetchModules);
for (int i = 0; i < jsonArray.length(); i++) {
modules.add(jsonArray.get(i).toString());
JSONObject jsonObject=new JSONObject();
String id=jsonObject.getString("id").toString();
Log.i("id", ":" + id);
String name=jsonObject.getString("name").toString();
Log.i("name", ":" + name);
String isEntity=jsonObject.getString("isEntity").toString();
String label=jsonObject.getString("label").toString();
Log.i("isEntity", ":" + isEntity);
String singular=jsonObject.getString("singular").toString();
Log.i("singular", ":" + singular);
}//end for
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}
LoginAndFetchModules.java:
public class LoginAndFetchModules {
#SerializedName("success")
private String success;
#SerializedName("result")
private List<Results> result;
public List<Results> getResult() {
return result;
}
public void setResult(List<Results> result) {
this.result = result;
}
public String getSuccess() {
return success;
}
public void setSuccess(String success) {
this.success = success;
}
}
Results.java:
public class Results {
#SerializedName("login")
#Expose
private GetLoginListDetails login;
#SerializedName("modules")
#Expose
private ArrayList<LoginListForModules> modules;
public ArrayList<LoginListForModules> getModules() {
return modules;
}
public void setModules(ArrayList<LoginListForModules> modules) {
this.modules = modules;
}
public GetLoginListDetails getLogin() {
return login;
}
public void setLogin(GetLoginListDetails login) {
this.login = login;
}
}
LoginListForModules.java:
public class LoginListForModules {
#SerializedName("id")
#Expose
private String id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("isEntity")
#Expose
private String isEntity;
#SerializedName("label")
#Expose
private String label;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIsEntity() {
return isEntity;
}
public void setIsEntity(String isEntity) {
this.isEntity = isEntity;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getSingular() {
return singular;
}
public void setSingular(String singular) {
this.singular = singular;
}
#SerializedName("singular")
#Expose
private String singular;
}
GetLoginListDetails .java:
public class GetLoginListDetails {
#SerializedName("session")
#Expose
private String session;
#SerializedName("userid")
#Expose
private String userid;
#SerializedName("vtiger_version")
#Expose
private String vtiger_version;
#SerializedName("mobile_module_version")
#Expose
private String mobile_module_version;
public String getSession() {
return session;
}
public void setSession(String session) {
this.session = session;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getVtiger_version() {
return vtiger_version;
}
public void setVtiger_version(String vtiger_version) {
this.vtiger_version = vtiger_version;
}
public String getMobile_module_version() {
return mobile_module_version;
}
public void setMobile_module_version(String mobile_module_version) {
this.mobile_module_version = mobile_module_version;
}
}
Expected output:
{
"success": true,
"result": {
"login": {
"userid": "1",
"session": "fa000f0a6c5a414e62dcc4cbf99175d6",
"vtiger_version": "5.2.0",
"mobile_module_version": "1.2.1"
},
"modules": [
{
"id": "1",
"name": "Calendar",
"isEntity": true,
"label": "Calendar",
"singular": "To Do"
},
{
"id": "2",
"name": "Leads",
"isEntity": true,
"label": "Leads",
"singular": "Lead"
},
{
"id": "3",
"name": "Accounts",
"isEntity": true,
"label": "Accounts",
"singular": "Account"
}]
}
}
According json response, it return Results instead of List. Change your LoginAndFetchModules like below:
public class LoginAndFetchModules {
#SerializedName("success")
private String success;
#SerializedName("result")
private Results result;
public Results getResult() {
return result;
}
public void setResult(Results result) {
this.result = result;
}
public String getSuccess() {
return success;
}
public void setSuccess(String success) {
this.success = success;
}
}
And then parse the informations like below:
if (response.isSuccessful()) {
LoginAndFetchModules loginAndFetchModules = response.body();
String success = loginAndFetchModules.getSuccess();
if (success.equals("true")) {
Results results = loginAndFetchModules.getResult();
//parse login details
GetLoginListDetails loginDetails = results.getLogin();
String userId = loginDetails.getUserid();
//parse modules
ArrayList<LoginListForModules> modules = results.getModules();
//parse module information
for(LoginListForModules module: modules) {
String id = module.getId();
String name = module.getName();
...
}
}
}
you can create classes for response like this
first class is ResultReponse
public class ResultReponse implements Serializable {
#SerializedName("success")
private boolean success;
#SerializedName("result")
private ResultBean result;
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public ResultBean getResult() {
return result;
}
public void setResult(ResultBean result) {
this.result = result;
}
}
ResultBean class
public class ResultBean implements Serializable{
#SerializedName("login")
private LoginBean login;
#SerializedName("modules")
private List<ModulesBean> modules;
public LoginBean getLogin() {
return login;
}
public void setLogin(LoginBean login) {
this.login = login;
}
public List<ModulesBean> getModules() {
return modules;
}
public void setModules(List<ModulesBean> modules) {
this.modules = modules;
}
}
loginBean class inside ResultBean
public class LoginBean implements Serializable {
#SerializedName("userid")
private String userid;
#SerializedName("session")
private String session;
#SerializedName("vtiger_version")
private String vtiger_version;
#SerializedName("mobile_module_version")
private String mobile_module_version;
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getSession() {
return session;
}
public void setSession(String session) {
this.session = session;
}
public String getVtiger_version() {
return vtiger_version;
}
public void setVtiger_version(String vtiger_version) {
this.vtiger_version = vtiger_version;
}
public String getMobile_module_version() {
return mobile_module_version;
}
public void setMobile_module_version(String mobile_module_version) {
this.mobile_module_version = mobile_module_version;
}
}
ModulesBean class in list
public class ModulesBean implements Serializable {
#SerializedName("id")
private String id;
#SerializedName("name")
private String name;
#SerializedName("isEntity")
private boolean isEntity;
#SerializedName("label")
private String label;
#SerializedName("singular")
private String singular;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isIsEntity() {
return isEntity;
}
public void setIsEntity(boolean isEntity) {
this.isEntity = isEntity;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getSingular() {
return singular;
}
public void setSingular(String singular) {
this.singular = singular;
}
}

Retrofit with Gson Response.body() not working

I'am trying to parse data to a recyclerview, i had some problems about expecting JSONArray/JSONObject that i fixed with some help, but this moment I am a little bit lost in what to do in the Onresponse, the original - generatePhonesList(response.body()) isnt working.
this is my json and i am trying to parse the data inside the array results[] :
{
"success": true,
"metadata": {
"sort": "POPULARITY",
"total_products": 20,
"title": "Phones & Tablets",
"results": [
{
"sku": "1",
"name": "Samsung Galaxy S9",
"brand": "Samsung",
"max_saving_percentage": 30,
"price": 53996,
"special_price": 37990,
"image": "https://cdn2.gsmarena.com/vv/bigpic/samsung-galaxy-s9-.jpg",
"rating_average": 5
},
MainActivity (CALL and Recyclerview creation) :
GetPhoneDataService service = RetrofitInstance.getRetrofitInstance().create(GetPhoneDataService.class);
Call<APIReponse> call = service.getAllPhones();
call.enqueue(new Callback<APIReponse>() {
#Override
public void onResponse(Call<APIReponse> call, Response<APIReponse> response) {
generatePhonesList(response.body());
}
#Override
public void onFailure(Call<APIReponse> call, Throwable t) {
Log.e("eee" , "" + t.getMessage());
}
});
}
private void generatePhonesList(List<Result> phonesList){
recyclerView = findViewById(R.id.recyclerView);
adapter = new PhonesAdapter(phonesList,this);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
}
this is the POJO Class's created in jsonschema2pojo :
public class APIReponse {
#SerializedName("success")
#Expose
private Boolean success;
#SerializedName("metadata")
#Expose
private Metadata metadata;
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public Metadata getMetadata() {
return metadata;
}
public void setMetadata(Metadata metadata) {
this.metadata = metadata;
}
}
2 class
public class MetaData {
#SerializedName("sort")
#Expose
private String sort;
#SerializedName("total_products")
#Expose
private Integer totalProducts;
#SerializedName("title")
#Expose
private String title;
#SerializedName("results")
#Expose
private List<Result> results = null;
public String getSort() {
return sort;
}
public void setSort(String sort) {
this.sort = sort;
}
public Integer getTotalProducts() {
return totalProducts;
}
public void setTotalProducts(Integer totalProducts) {
this.totalProducts = totalProducts;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<Result> getResults() {
return results;
}
public void setResults(List<Result> results) {
this.results = results;
}
}
3 class:
public class Result {
#SerializedName("sku")
#Expose
private String sku;
#SerializedName("name")
#Expose
private String name;
#SerializedName("brand")
#Expose
private String brand;
#SerializedName("max_saving_percentage")
#Expose
private Integer maxSavingPercentage;
#SerializedName("price")
#Expose
private Integer price;
#SerializedName("special_price")
#Expose
private Integer specialPrice;
#SerializedName("image")
#Expose
private String image;
#SerializedName("rating_average")
#Expose
private Integer ratingAverage;
public String getSku() {
return sku;
}
public void setSku(String sku) {
this.sku = sku;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public Integer getMaxSavingPercentage() {
return maxSavingPercentage;
}
public void setMaxSavingPercentage(Integer maxSavingPercentage) {
this.maxSavingPercentage = maxSavingPercentage;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
public Integer getSpecialPrice() {
return specialPrice;
}
public void setSpecialPrice(Integer specialPrice) {
this.specialPrice = specialPrice;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public Integer getRatingAverage() {
return ratingAverage;
}
public void setRatingAverage(Integer ratingAverage) {
this.ratingAverage = ratingAverage;
}
}
You are passing the APIReponse model to the generatePhonesList(List<Result> phonesList) function. You need to pass only the list of results in this function.
Replace this:
generatePhonesList(response.body());
with:
generatePhonesList(response.body().getMetadata().getResults());
Here getMetadata() and getResults() are the getter functions of metadata model and List.
If you pay close attention response.body() will provide you with class APIResponse. But you need is List<Result>. To achieve this, try response.body().getMetadata().getResults()
This should give you the desired output.

success is false from server

Hi in the below code success is false from server while parsing json data.status code is 200 and created.
Login Modules class contains list of strings and GetModuleList contains a list of strings but in the modules is an array it contains a list of objects
LoginModules.java:
public class LoginModules {
#SerializedName("success")
private String success;
#SerializedName("result")
private List<GetLoginModuleList> result;
public List<GetLoginModuleList> getResult() {
return result;
}
public void setResult(List<GetLoginModuleList> result) {
this.result = result;
}
public String getSuccess() {
return success;
}
public void setSuccess(String success) {
this.success = success;
}
}
GetLoginModuleList.java:
public class GetLoginModuleList {
#SerializedName("session")
#Expose
private String session;
#SerializedName("userid")
#Expose
private String userid;
#SerializedName("vtiger_version")
#Expose
private String vtiger_version;
#SerializedName("modules")
#Expose
private List<Modules> modules;
public List<Modules> getModules() {
return modules;
}
public void setModules(List<Modules> modules) {
this.modules = modules;
}
public String getSession() {
return session;
}
public void setSession(String session) {
this.session = session;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getVtiger_version() {
return vtiger_version;
}
public void setVtiger_version(String vtiger_version) {
this.vtiger_version = vtiger_version;
}
public String getMobile_module_version() {
return mobile_module_version;
}
public void setMobile_module_version(String mobile_module_version) {
this.mobile_module_version = mobile_module_version;
}
#SerializedName("mobile_module_version")
#Expose
private String mobile_module_version;
}
GetLoginModulesList.java:
public class GetLoginModuleList {
#SerializedName("login")
private GetLoginList login;
public GetLoginList getLogin() {
return login;
}
public void setLogin(GetLoginList login) {
this.login = login;
}
public List<Modules> getModules() {
return modules;
}
public void setModules(List<Modules> modules) {
this.modules = modules;
}
#SerializedName("modules")
private List<Modules> modules;
}
Modules.java:
public class Modules {
#SerializedName("id")
#Expose
private String id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("isEntity")
#Expose
private String isEntity;
#SerializedName("label")
#Expose
private String label;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIsEntity() {
return isEntity;
}
public void setIsEntity(String isEntity) {
this.isEntity = isEntity;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getSingular() {
return singular;
}
public void setSingular(String singular) {
this.singular = singular;
}
#SerializedName("singular")
#Expose
private String singular;
}
Json response:
{
"success": true,
"result": {
"login": {
"userid": "1",
"session": "fa000f0a6c5a414e62dcc4cbf99175d6",
"vtiger_version": "5.2.0",
"mobile_module_version": "1.2.1"
},
"modules": [
{
"id": "1",
"name": "Calendar",
"isEntity": true,
"label": "Calendar",
"singular": "To Do"
},
{
"id": "2",
"name": "Leads",
"isEntity": true,
"label": "Leads",
"singular": "Lead"
},
]
}
}
Activity.java:
if (response.isSuccessful()) {
LoginModules loginModules = response.body();
String success = loginModules.getSuccess()
.toString();
if (success.equals("true")) {
String result = loginModules.getResult()
.toString();
Log.i("result", ":" + result);
String Userid = loginModules.getResult()
.getUserid();
Log.i("Userid", ":" + Userid);
String Session = loginModules.getResult()
.getSession();
Log.i("Session", ":" + Session);
String Vtiger_version = loginModules.getResult()
.getVtiger_version();
Log.i("Vtiger_version", ":" + Vtiger_version);
String Mobile_module_version = loginModules.getResult()
.getMobile_module_version();
Log.i("Mobile_module_version", ":" + Mobile_module_version);
//List<Modules> modules = new ArrayList<>();
//Gson gson = new Gson();
JSONArray jsonarray = null;
try {
jsonarray = new JSONArray("modules");
} catch (JSONException e) {
e.printStackTrace();
}
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = null;
try {
jsonobject = jsonarray.getJSONObject(i);
String id = jsonobject.getString("id");
Log.i("id", ":" + id);
// String url = jsonobject.getString("url");
} catch (JSONException e) {
e.printStackTrace();
}
}
if (username.equals("admin") && pass.equals("Password!1")) {
Toast.makeText(getApplicationContext(), "Login Successfully", Toast.LENGTH_LONG)
.show();
Intent i = new Intent(LoginActivity.this, MainActivity.class);
startActivity(i);
finish();
} else {
Toast.makeText(getApplicationContext(), "Invalid Username and Password", Toast.LENGTH_LONG)
.show();
}
}
}
Some data is missing in your model structure for parsing data.
"result": {
"login": {
"userid": "1",
"session": "fa000f0a6c5a414e62dcc4cbf99175d6",
"vtiger_version": "5.2.0",
"mobile_module_version": "1.2.1"
},
there is a "login" jsonobject in your "result" object. But you missed the "login" element when you parse it. you should create a java class as LoginModel.
public class LoginModel {
#SerializedName("session")
#Expose
private String session;
#SerializedName("userid")
#Expose
private String userid;
#SerializedName("vtiger_version")
#Expose
private String vtiger_version;
and put login model in your GetModuleList class.
public class GetLoginModuleList {
#SerializedName("login")
#Expose
private LoginModel login;

How to convert Json into a Java bean object?

I am trying to convert a complex object into related Java beans. However, some sub class can be not generated correctly.
I am just using simulate MS Adaptive card to create a set of Java beans classes. When I call Gson package or Alibaba fastJson package to parse my json data. it always shows the super class type.
This is just an experiment to test Gson & fastJson whether it can convert complex objects. which is running on the Android studio.
My demo json is like following:
{
"type": "AdaptiveCard",
"version": "1.0",
"id": "workloadQCactivity 20",
"speak": "activity 20 <break time=\"300ms\"/> at<break time=\"300ms\"/> <break time=\"300ms\"/>building<break time=\"300ms\"/>A<break time=\"300ms\"/>floor<break time=\"300ms\"/>1<break time=\"300ms\"/>room<break time=\"300ms\"/>1<break time=\"300ms\"/> ",
"body": [{
"type": "Container",
"items": [{
"type": "ColumnSet",
"columns": [{
"type": "Column",
"width": "Stretch",
"items": [{
"type": "TextBlock",
"size": "large",
"weight": "bolder",
"text": "activity 20 at building A floor 1 room 1",
"wrap": true
}]
}]
}]
}],
"actions": [{
"type": "Action.ShowCard",
"card": {
"type": "AdaptiveCard",
"version": "1.0",
"body": [{
"type": "TextBlock",
"size": "medium",
"weight": "bolder",
"isSubtle": true,
"text": "have thing to check list1",
"wrap": true
}, {
"type": "TextBlock",
"weight": "bolder",
"isSubtle": true,
"text": "this is section 1",
"wrap": true
}, {
"type": "TextBlock",
"isSubtle": true,
"text": "q1 of s1",
"wrap": true
}, {
"type": "TextBlock",
"isSubtle": true,
"text": "q2 of s2",
"wrap": true
}, {
"type": "TextBlock",
"weight": "bolder",
"isSubtle": true,
"text": "this is section 2",
"wrap": true
}, {
"type": "TextBlock",
"isSubtle": true,
"text": "q1 of s22",
"wrap": true
}, {
"type": "TextBlock",
"size": "medium",
"weight": "bolder",
"isSubtle": true,
"text": "have checklist 2",
"wrap": true
}, {
"type": "TextBlock",
"weight": "bolder",
"isSubtle": true,
"text": "section of the second checklist",
"wrap": true
}, {
"type": "TextBlock",
"isSubtle": true,
"text": "qqqqqq",
"wrap": true
}]
},
"title": "Show Checklist"
}]
}
Therefore, I just follow MS adaptive card to create following java beans.
First class: AdaptiveTypedElement
public class AdaptiveTypedElement {
#JsonProperty("additionalPorperties")
public Map<String, Object> additionalPorperties = new HashMap<String, Object>();
//#JsonProperty("type")
//public String type;
#JsonProperty("id")
public String id;
}
Second class: AdaptiveTypedElement
public class AdaptiveElement extends AdaptiveTypedElement {
#JsonProperty("spacing")
public AdaptiveSpacing spacing ;
#JsonProperty("separator")
public boolean separator = false;
#JsonProperty("speak")
public String speak;
#JsonProperty("separation")
// public AdaptiveSeparationStyle separation;
public String separation;
}
Third class AdaptiveContainer:
public class AdaptiveContainer extends AdaptiveElement {
#JsonProperty("typeName")
public String typeName = "Container";
#JsonProperty("type")
public String type = "Container";
#JsonProperty("items")
public List<AdaptiveElement> items = new ArrayList<AdaptiveElement>();
#JsonProperty("selectAction")
public AdaptiveAction selectAction = null;
#JsonProperty("style")
public AdaptiveContainerStyle style = AdaptiveContainerStyle.Default;
}
public class AdaptiveColumnSet extends AdaptiveElement {
#JsonProperty("typeName")
public final String typeName = "ColumnSet";
#JsonProperty("type")
public final String type = "ColumnSet";
#JsonProperty("columns")
public List<AdaptiveColumn> columns = new ArrayList<AdaptiveColumn>();
#JsonProperty("selectionAction")
public AdaptiveAction selectionAction = null;
}
public class AdaptiveColumn extends AdaptiveContainer{
#JsonProperty("typeName")
public final String typeName = "Column";
#JsonProperty("type")
public final String type = "Column";
#JsonProperty("size")
public String size;
#JsonProperty("with")
public String with;
}
public class AdaptiveAction {
#JsonProperty("title")
public String title;
#JsonProperty("speak")
public String speak;
}
public class AdaptiveShowCardAction extends AdaptiveAction {
#JsonProperty("typeName")
public final String typeName = "Action.ShowCard";
#JsonProperty("type")
public final String Type = "Action.ShowCard";
#JsonProperty("card")
public AdaptiveCard card;
}
public class AdaptiveTextBlock extends AdaptiveElement{
#JsonProperty("typeName")
public String typeName = "TextBlock";
#JsonProperty("type")
public String type = "TextBlock";
#JsonProperty("text")
public String text = "";
#JsonProperty("size")
public AdaptiveTextSize size;
#JsonProperty("weight")
public AdaptiveTextWeight weight;
#JsonProperty("color")
public AdaptiveTextColor color;
#JsonProperty("horizontalAlignment")
public AdaptiveHorizontalAlignment horizontalAlignment = AdaptiveHorizontalAlignment.Left;
#JsonProperty("wrap")
public boolean wrap = false;
#JsonProperty("isSubtle")
public boolean isSubtle = false;
#JsonProperty("maxLines")
public int maxLines = 0;
#JsonProperty("maxWidth")
public int maxWidth = 0;
}
public class AdaptiveCard extends AdaptiveTypedElement {
#JsonProperty("contentType")
public final String contentType = "application/vnd.microsoft.card.adaptive";
#JsonProperty("typeName")
public final String typeName = "AdaptiveCard";
#JsonProperty("type")
public String type = "AdaptiveCard";
#JsonProperty("body")
public List<AdaptiveElement> body = new ArrayList<AdaptiveElement>();
#JsonProperty("actions")
public List<AdaptiveAction> actions = new ArrayList<AdaptiveAction>();
#JsonProperty("speak")
public String speak = null;
#JsonProperty("title")
public String title;
#JsonProperty("version")
//public AdaptiveSchemaVersion version = null;
public String version = null;
#JsonProperty("fallbackText")
public String fallbackText = null;
#JsonProperty("lang")
public String lang = null;
}
In the end, I finally got AdaptiveCard Object. See my code:
return JSON.parseObject(attachJson, AdaptiveCard.class). Note that I add "implementation 'com.alibaba:fastjson:1.2.54'" in my Android Studio
When I check this object, I found the Body data member should be class "AdaptiveContainer " not "AdaptiveElement". I was wondering why it did not following subclass mechanism of OOP & OOD. I am expecting "AdaptiveContainer", but actually output is "AdaptiveElement".
enter image description here
rib-pet, your question has a far to big example. Anyway I tried to create a java class mapping for your sample using GSON
Action.java
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Action {
#SerializedName("type")
#Expose
private String type;
#SerializedName("card")
#Expose
private Card card;
#SerializedName("title")
#Expose
private String title;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Card getCard() {
return card;
}
public void setCard(Card card) {
this.card = card;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
Body.java
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Body {
#SerializedName("type")
#Expose
private String type;
#SerializedName("items")
#Expose
private List<Item> items = null;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
}
Body_.java (dependend on your wished model you should integrate this class better in some existing
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Body_ {
#SerializedName("type")
#Expose
private String type;
#SerializedName("size")
#Expose
private String size;
#SerializedName("weight")
#Expose
private String weight;
#SerializedName("isSubtle")
#Expose
private Boolean isSubtle;
#SerializedName("text")
#Expose
private String text;
#SerializedName("wrap")
#Expose
private Boolean wrap;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public Boolean getIsSubtle() {
return isSubtle;
}
public void setIsSubtle(Boolean isSubtle) {
this.isSubtle = isSubtle;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Boolean getWrap() {
return wrap;
}
public void setWrap(Boolean wrap) {
this.wrap = wrap;
}
}
Card.java
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Card {
#SerializedName("type")
#Expose
private String type;
#SerializedName("version")
#Expose
private String version;
#SerializedName("body")
#Expose
private List<Body_> body = null;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public List<Body_> getBody() {
return body;
}
public void setBody(List<Body_> body) {
this.body = body;
}
}
Column.java
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Column {
#SerializedName("type")
#Expose
private String type;
#SerializedName("width")
#Expose
private String width;
#SerializedName("items")
#Expose
private List<Item_> items = null;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getWidth() {
return width;
}
public void setWidth(String width) {
this.width = width;
}
public List<Item_> getItems() {
return items;
}
public void setItems(List<Item_> items) {
this.items = items;
}
}
Example.java
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("type")
#Expose
private String type;
#SerializedName("version")
#Expose
private String version;
#SerializedName("id")
#Expose
private String id;
#SerializedName("speak")
#Expose
private String speak;
#SerializedName("body")
#Expose
private List<Body> body = null;
#SerializedName("actions")
#Expose
private List<Action> actions = null;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSpeak() {
return speak;
}
public void setSpeak(String speak) {
this.speak = speak;
}
public List<Body> getBody() {
return body;
}
public void setBody(List<Body> body) {
this.body = body;
}
public List<Action> getActions() {
return actions;
}
public void setActions(List<Action> actions) {
this.actions = actions;
}
}
Item.java
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Item {
#SerializedName("type")
#Expose
private String type;
#SerializedName("columns")
#Expose
private List<Column> columns = null;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public List<Column> getColumns() {
return columns;
}
public void setColumns(List<Column> columns) {
this.columns = columns;
}
}
Item_.java also here better integration needed
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Item_ {
#SerializedName("type")
#Expose
private String type;
#SerializedName("size")
#Expose
private String size;
#SerializedName("weight")
#Expose
private String weight;
#SerializedName("text")
#Expose
private String text;
#SerializedName("wrap")
#Expose
private Boolean wrap;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Boolean getWrap() {
return wrap;
}
public void setWrap(Boolean wrap) {
this.wrap = wrap;
}
}
hope it helps!
I've figured out this solution via the following solution:
JSONObject and JSONArray
JSONArray body = contentObj.getJSONArray("body");
JSONArray actions = contentObj.getJSONArray("actions");
title.setText(body.getJSONObject(0).getString("text"));

Categories

Resources