Parsing and storing a json response in android - java

My JSON response has the following structure.
How should i parse it to store in a list in java with the structure maintained.
Does GSON provide a solution or should i use multidimensional array list?
I need to pass each of the tag array to a different view pager what approach should I follow.
{
"tag": [
{
"listing_count": 5,
"listings": [
{
"source": "source1",
"data": {
"image": "image1",
"name": "name1"
},
"name": "name1"
}
]
},
{
"listing_count": 5,
"listings": [
{
"source": "source2",
"data": {
"image": "imag2",
"name": "name2"
},
"name": "name2"
}
]
}
]
}
EDIT:
I have created the classes as suggested in the answer..I am having trouble creating the GSON response class.
This is what I have created:
public GsonRequest(int method, String url, Class<T> clazz,
Listener<T> listener, ErrorListener errorListener, Gson gson) {
super(Method.GET, url, errorListener);
this.mClazz = clazz;
this.mListener = listener;
mGson = gson;
}

The gson class should be something like this:
public class TagList {
ArrayList<Tag> tags;
public static class Tag {
int listing_count;
ArrayList<Listings> listings;
public int getListing_count() {
return listing_count;
}
public void setListing_count(int listing_count) {
this.listing_count = listing_count;
}
public ArrayList<Listings> getListings() {
return listings;
}
public void setListings(ArrayList<Listings> listings) {
this.listings = listings;
}
}
public static class Listings {
String source;
Data data;
String name;
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public static class Data {
String image;
String name;
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

Related

Getting Json object and Json Array in Same KEY

I am getting JSON Object when their is only one response(Plan) and JSON Array when their is more than one response(plan).How to handle JSON Response?
JSON ARRAY when their is more than one plan.
{
"ocrNumber": "0123456",
"userName": "dddd",
"plan": [{
"lat": "13.1234",
"long": "7.1234",
"imagepath": "sd / image / demo.jpg"
},{
"lat": "13.1234",
"long": "7.1234",
"imagepath": "sd / image / demo.jpg"
}]
}
JSON OBJECT when their is only one plan.
{
"ocrNumber": "0123456",
"userName": "dddd",
"plan": {
"lat": "13.1234",
"long": "7.1234",
"imagepath": "sd / image / demo.jpg"
}
}
add dependencies in your app level gradle file.
implementation 'com.google.code.gson:gson:2.8.5'
Create MyResponse.java
public class MyResponse {
#SerializedName("ocrNumber")
private String ocrNumber;
#SerializedName("userName")
private String userName;
#SerializedName("plan")
private ArrayList<Plan> plan;
public String getOcrNumber() {
return ocrNumber;
}
public void setOcrNumber(String ocrNumber) {
this.ocrNumber = ocrNumber;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public ArrayList<Plan> getPlan() {
return plan;
}
public void setPlan(ArrayList<Plan> plan) {
this.plan = plan;
}
}
create Plan.java class
public class Plan {
#SerializedName("lat")
private String lat;
#SerializedName("long")
private String longStr;
#SerializedName("imagepath")
private String imagepath;
public String getLat() {
return lat;
}
public void setLat(String lat) {
this.lat = lat;
}
public String getLongStr() {
return longStr;
}
public void setLongStr(String longStr) {
this.longStr = longStr;
}
public String getImagepath() {
return imagepath;
}
public void setImagepath(String imagepath) {
this.imagepath = imagepath;
}
}
Convert your jsonString to object using Gson
Gson gson = new Gson();
MyResponse response = gson.fromJson(yourJsonString, MyResponse.class);

Parse Json array with multiple objects using retrofit 2 in android

I'm using retrofit 2 for networking functions in my project, and I'm able to parse the json object responses from the server but now I'm supposed to parse a json array that look like this
[
{
"id_asset": 1,
"id_category": 1,
"id_brand": 2,
"name": "Samsung Galaxy 6",
"status": 1,
"updated_at": "Oct 3, 2016 10:24:28 AM",
"rank": 1,
"rate": {
"id_asset_rate": 2,
"id_asset": 1,
"value": 5000,
"loan_to_value": 50,
"offered": 2500,
"annual_rate": 3,
"quantity": 5,
"created_at": "Oct 23, 2016 5:31:31 AM",
"updated_at": "Oct 23, 2016 5:32:31 AM"
},
"best_rate": {
"id_asset": "1",
"value": "5000",
"loan_to_value": "50",
"offered": "2500",
"annual_rate": "3",
"quantity": "5",
"rank": "1"
},
"category": {
"id_category": 1,
"id_parent": 0,
"name": "Mobile Phones",
"image": "",
"sort": 1,
"status": 1,
"created_at": null,
"updated_at": null,
"_links": {
"self": {
"href": "/v1/categories/1"
}
}
},
"brand": {
"id_brand": 2,
"name": "Samsung",
"status": 1,
"created_at": null,
"updated_at": null
},
"_links": {
"self": {
"href": "/v1/assets/1"
}
}
},
{
"id_asset": 2,
"id_category": 1,
"id_brand": 1,
"name": "i Phone 5",
"status": 1,
"updated_at": "Oct 3, 2016 8:04:36 AM",
"rank": false,
"rate": null,
"best_rate": false,
"category": {
"id_category": 1,
"id_parent": 0,
"name": "Mobile Phones",
"image": "",
"sort": 1,
"status": 1,
"created_at": null,
"updated_at": null,
"_links": {
"self": {
"href": "/v1/categories/1"
}
}
},
"brand": {
"id_brand": 1,
"name": "Apple",
"status": 1,
"created_at": null,
"updated_at": null
},
"_links": {
"self": {
"href": "/v1/assets/2"
}
}
}
]
This is the response from the server and I created this POJO for the response
public class AssetResponse {
private Integer id_asset;
private Integer id_category;
private Integer id_brand;
private String name;
private Integer status;
private String updated_at;
private AssetRate assetRate;
private AssetCategory assetCategory;
private Links links;
private Self self;
private AssetBrand assetBrand;
private HasLinked hasLinked;
public Integer getId_asset() {
return id_asset;
}
public void setId_asset(Integer id_asset) {
this.id_asset = id_asset;
}
public Integer getId_category() {
return id_category;
}
public void setId_category(Integer id_category) {
this.id_category = id_category;
}
public Integer getId_brand() {
return id_brand;
}
public void setId_brand(Integer id_brand) {
this.id_brand = id_brand;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getUpdated_at() {
return updated_at;
}
public void setUpdated_at(String updated_at) {
this.updated_at = updated_at;
}
public AssetRate getAssetRate() {
return assetRate;
}
public void setAssetRate(AssetRate assetRate) {
this.assetRate = assetRate;
}
public AssetCategory getAssetCategory() {
return assetCategory;
}
public void setAssetCategory(AssetCategory assetCategory) {
this.assetCategory = assetCategory;
}
public Links getLinks() {
return links;
}
public void setLinks(Links links) {
this.links = links;
}
public Self getSelf() {
return self;
}
public void setSelf(Self self) {
this.self = self;
}
public AssetBrand getAssetBrand() {
return assetBrand;
}
public void setAssetBrand(AssetBrand assetBrand) {
this.assetBrand = assetBrand;
}
public HasLinked getHasLinked() {
return hasLinked;
}
public void setHasLinked(HasLinked hasLinked) {
this.hasLinked = hasLinked;
}
private class AssetRate {
private Integer id_asset_rate;
private Integer id_asset;
private Double value;
private Double loan_to_value;
private Double offered;
private Double annual_rate;
private String updated_at;
public Integer getId_asset_rate() {
return id_asset_rate;
}
public void setId_asset_rate(Integer id_asset_rate) {
this.id_asset_rate = id_asset_rate;
}
public Integer getId_asset() {
return id_asset;
}
public void setId_asset(Integer id_asset) {
this.id_asset = id_asset;
}
public Double getValue() {
return value;
}
public void setValue(Double value) {
this.value = value;
}
public Double getLoan_to_value() {
return loan_to_value;
}
public void setLoan_to_value(Double loan_to_value) {
this.loan_to_value = loan_to_value;
}
public Double getOffered() {
return offered;
}
public void setOffered(Double offered) {
this.offered = offered;
}
public Double getAnnual_rate() {
return annual_rate;
}
public void setAnnual_rate(Double annual_rate) {
this.annual_rate = annual_rate;
}
public String getUpdated_at() {
return updated_at;
}
public void setUpdated_at(String updated_at) {
this.updated_at = updated_at;
}
}
private class AssetCategory {
private Integer id_category;
private Integer id_parent;
private String name;
private String image;
private Integer sort;
private Integer status;
private String created_at;
private String updated_at;
private Links links;
public Integer getId_category() {
return id_category;
}
public void setId_category(Integer id_category) {
this.id_category = id_category;
}
public Integer getId_parent() {
return id_parent;
}
public void setId_parent(Integer id_parent) {
this.id_parent = id_parent;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public Integer getSort() {
return sort;
}
public void setSort(Integer sort) {
this.sort = sort;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getCreated_at() {
return created_at;
}
public void setCreated_at(String created_at) {
this.created_at = created_at;
}
public String getUpdated_at() {
return updated_at;
}
public void setUpdated_at(String updated_at) {
this.updated_at = updated_at;
}
public Links getLinks() {
return links;
}
public void setLinks(Links links) {
this.links = links;
}
}
private class Links {
#SerializedName("self")
#Expose
private Self self;
/**
*
* #return
* The self
*/
public Self getSelf() {
return self;
}
/**
*
* #param self
* The self
*/
public void setSelf(Self self) {
this.self = self;
}
}
private class Self {
#SerializedName("href")
#Expose
private String href;
/**
*
* #return
* The href
*/
public String getHref() {
return href;
}
/**
*
* #param href
* The href
*/
public void setHref(String href) {
this.href = href;
}
}
private class AssetBrand {
private Integer id_brand;
private String name;
private Integer status;
private String created_at;
private String updated_at;
public Integer getId_brand() {
return id_brand;
}
public void setId_brand(Integer id_brand) {
this.id_brand = id_brand;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getCreated_at() {
return created_at;
}
public void setCreated_at(String created_at) {
this.created_at = created_at;
}
public String getUpdated_at() {
return updated_at;
}
public void setUpdated_at(String updated_at) {
this.updated_at = updated_at;
}
}
private class HasLinked {
private Integer has_linked;
private Links links;
public Integer getHas_linked() {
return has_linked;
}
public void setHas_linked(Integer has_linked) {
this.has_linked = has_linked;
}
public Links getLinks() {
return links;
}
public void setLinks(Links links) {
this.links = links;
}
}
}
}
Is my pojo is right ?
My problem is, I can't parse this response. Any help will be appreciated.
Thanks in advance
EDIT :
This is my request to server (using rest api)
#GET("url")
Call<AssetResponse> getAssetList();
EDIT 2: I've changed the code to List, as suggested by Niko Adrianus Yuwono.
This is the new changes
private void getAssets() {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(logging);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient.build())
.build();
final ApiInterface apiInterface = retrofit.create(ApiInterface.class);
final AssetRequest assetRequest = new AssetRequest();
assetRequest.setAcc_tok(ACCESS_TOKEN);
final Call<List<AssetResponse>> assetList = apiInterface.getAssetList();
assetList.enqueue(new Callback <List<AssetResponse>>() {
#Override
public void onResponse(Call<List<AssetResponse>> call, Response<List<AssetResponse>> response) {
int statusCode = response.code();
List<AssetResponse> assetResponseList = response.body();
if (statusCode == 200) {
for (int i = 0; i < assetResponseList.size(); i++ ){
Integer id_asset = assetResponseList.get(i).getId_asset();
Integer id_category = assetResponseList.get(i).getId_category();
Integer status = assetResponseList.get(i).getStatus();
String name = assetResponseList.get(i).getName();
Log.d("Assets ","Asset id_asset bb : " + id_asset);
Log.d("Assets ","Asset id_category bb : " + id_category);
Log.d("Assets ","Asset name bb : " + name);
Log.d("Assets ","Asset status bb : " + status);
Double val = assetResponseList.get(i).getAssetRate().getValue();
Log.d("val ","val is : " +val);
}
} else {
Toast.makeText(getContext(), "network error " + statusCode, Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<List<AssetResponse>> call, Throwable t) {
Log.d("Asset GET Failure", "onFailure: " + t.getMessage());
//showProgress(false);
}
});
}
and this is the response from the server
D/Assets: Asset id_asset bb : 1 D/Assets: Asset id_category bb : 1 D/Assets: Asset name bb : Samsung Galaxy 6 D/Assets: Asset status
bb : 1 10-26 13:13:17.898 22784-22784/ D/AndroidRuntime: Shutting down
VM 10-26 13:13:17.898 22784-22784/ E/AndroidRuntime: FATAL EXCEPTION:
main Process: , PID: 22784 java.lang.NullPointerException: Attempt to
invoke virtual method 'java.lang.Double
.api.model.AssetResponse$AssetRate.getValue()' on a null object
reference
.AssetDatabaseFragment$2.onResponse(AssetDatabaseFragment.java:133)
retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:68)
android.os.Handler.handleCallback(Handler.java:739)
android.os.Handler.dispatchMessage(Handler.java:95)
android.os.Looper.loop(Looper.java:148)
android.app.ActivityThread.main(ActivityThread.java:5417)
java.lang.reflect.Method.invoke(Native Method)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Whenever I access the inner objects it throws error like the above
Your POJO looks right, but your JSON response is a JSONArray so you need to declare it as a List of Objects rather than an Object
#GET("url")
Call<List<AssetResponse>> getAssetList();
And you need to change your inner class access to public so GSON can see the setter and getter of that class.
Your Json key value data is changing from one index to another.
Wrong Json:
[{
//Make this either integer or boolean
"rank": 1,
// best rate is object here in the next index, it's treated as boolean.
"best_rate": {
"id_asset": "1",
"value": "5000",
"loan_to_value": "50",
"offered": "2500",
"annual_rate": "3",
"quantity": "5",
"rank": "1"
}
},
{
"rank":false,
"best_rate":false,
}
]
I have a complete project shared on github with your json.
https://github.com/lingarajsankaravelu/retrofit2v.git
Retrofit code should be like this as i mentioned in the question comment.
#GET("url")
Call<List<AssetResponse>> getAssetList();
As you have requested to explain the changes in your pojo class it should be like this.
AssetReponse.class:
public class AssetResponse {
private Integer id_asset;
private Integer id_category;
private Integer id_brand;
private String name;
private Integer status;
private String updated_at;
private AssetRate assetRate;
private AssetCategory assetCategory;
private Links links;
private Self self;
private AssetBrand assetBrand;
private HasLinked hasLinked;
public Integer getId_asset() {
return id_asset;
}
public void setId_asset(Integer id_asset) {
this.id_asset = id_asset;
}
public Integer getId_category() {
return id_category;
}
public void setId_category(Integer id_category) {
this.id_category = id_category;
}
public Integer getId_brand() {
return id_brand;
}
public void setId_brand(Integer id_brand) {
this.id_brand = id_brand;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getUpdated_at() {
return updated_at;
}
public void setUpdated_at(String updated_at) {
this.updated_at = updated_at;
}
public AssetRate getAssetRate() {
return assetRate;
}
public void setAssetRate(AssetRate assetRate) {
this.assetRate = assetRate;
}
public AssetCategory getAssetCategory() {
return assetCategory;
}
public void setAssetCategory(AssetCategory assetCategory) {
this.assetCategory = assetCategory;
}
public Links getLinks() {
return links;
}
public void setLinks(Links links) {
this.links = links;
}
public Self getSelf() {
return self;
}
public void setSelf(Self self) {
this.self = self;
}
public AssetBrand getAssetBrand() {
return assetBrand;
}
public void setAssetBrand(AssetBrand assetBrand) {
this.assetBrand = assetBrand;
}
public HasLinked getHasLinked() {
return hasLinked;
}
public void setHasLinked(HasLinked hasLinked) {
this.hasLinked = hasLinked;
}
}
AssetRate.class
public class AssetRate {
private Integer id_asset_rate;
private Integer id_asset;
private Double value;
private Double loan_to_value;
private Double offered;
private Double annual_rate;
private String updated_at;
public Integer getId_asset_rate() {
return id_asset_rate;
}
public void setId_asset_rate(Integer id_asset_rate) {
this.id_asset_rate = id_asset_rate;
}
public Integer getId_asset() {
return id_asset;
}
public void setId_asset(Integer id_asset) {
this.id_asset = id_asset;
}
public Double getValue() {
return value;
}
public void setValue(Double value) {
this.value = value;
}
public Double getLoan_to_value() {
return loan_to_value;
}
public void setLoan_to_value(Double loan_to_value) {
this.loan_to_value = loan_to_value;
}
public Double getOffered() {
return offered;
}
public void setOffered(Double offered) {
this.offered = offered;
}
public Double getAnnual_rate() {
return annual_rate;
}
public void setAnnual_rate(Double annual_rate) {
this.annual_rate = annual_rate;
}
public String getUpdated_at() {
return updated_at;
}
public void setUpdated_at(String updated_at) {
this.updated_at = updated_at;
}
}
Seperate your inner class like above. Seperating your inner class model will be useful if you are working on a large project. where you don't have to write the same pojo class again. you can use this seperate class structure instead.
You can use this site to generate POJO class. Just enter your JSON response and choose which JSON type you using like GSON,Jackson.etc. and You get perfect POJO classes. no need to change anything.
http://www.jsonschema2pojo.org/
Your Retrofit interface should be
#GET("url")
Call<List<AssetReponse>> getAssessList();
And make sure that your variable name same with key on JSON Response Or you can use annotation #SerializedName for that & for make it simple you can use JSON to POJO Online converter : http://www.jsonschema2pojo.org/

Rest Assured - Post nested POJO in Body

I'm trying to write an API class to send requests and handle responses from an API. Parts of the API have requests that require JSON bodies attached to the request such as this sample:
{
"Title": "string",
"Status": "string",
"ActFinish": "Date",
"ActHrs": "float",
"ActStart": "Date",
"ActualResults": "string",
"AssigneeUserId": "int",
"CustomFields": [
{
"Id": "string",
"Name": "string",
"Value": "string"
}
],
"Description": "string",
"EstFinish": "Date",
"EstHrs": "float",
"EstHrsRemaining": "float",
"EstStart": "Date",
"ExpectedResults": "string",
"FolderId": "int",
"FunctionalAreaCode": "string",
"HowFoundCode": "string",
"IssueCode": "string",
"ModuleCode": "string",
"PctComplete": "int",
"PriorityCode": "string",
"Resolution": "string",
"ResolutionCode": "string",
"SeverityCode": "string",
"SoftwareVersionCode": "string",
"StepsToRepro": "string"
}
The best way to do this I found through reading the Rest Assured documentation is with POJOs mentioned here: https://github.com/rest-assured/rest-assured/wiki/Usage#serialization
My POJO looks like this:
public class RequestDefectPost {
public String title;
public String status;
public Timestamp actFinish;
public float actHours;
public Timestamp actStart;
public String actualResults;
public int assigneeUserId;
public String[] customFields;
public String id;
public String name;
public String value;
public String description;
public Timestamp estFinish;
public float estHours;
public float estHrsRemaining;
public Timestamp estStart;
public String expectedResults;
public int folderId;
public String functionalAreaCode;
public String howFoundCode;
public String issueCode;
public String moduleCode;
public int pctComplete;
public String priorityCode;
public String resolutionCode;
public String severityCode;
public String softwareVersionCode;
public String stepsToRepro;
public RequestDefectPost(String title, String status) {
this.title = title;
this.status = status;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Timestamp getActFinish() {
return actFinish;
}
public void setActFinish(Timestamp actFinish) {
this.actFinish = actFinish;
}
public float getActHours() {
return actHours;
}
public void setActHours(float actHours) {
this.actHours = actHours;
}
public Timestamp getActStart() {
return actStart;
}
public void setActStart(Timestamp actStart) {
this.actStart = actStart;
}
public String getActualResults() {
return actualResults;
}
public void setActualResults(String actualResults) {
this.actualResults = actualResults;
}
public int getAssigneeUserId() {
return assigneeUserId;
}
public void setAssigneeUserId(int assigneeUserId) {
this.assigneeUserId = assigneeUserId;
}
public String[] getCustomFields() {
return customFields;
}
public void setCustomFields(String id, String name, String value) {
this.customFields = new String[]{this.id = id, this.name = name, this.value = value};
}
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 getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Timestamp getEstFinish() {
return estFinish;
}
public void setEstFinish(Timestamp estFinish) {
this.estFinish = estFinish;
}
public float getEstHours() {
return estHours;
}
public void setEstHours(float estHours) {
this.estHours = estHours;
}
public float getEstHrsRemaining() {
return estHrsRemaining;
}
public void setEstHrsRemaining(float estHrsRemaining) {
this.estHrsRemaining = estHrsRemaining;
}
public Timestamp getEstStart() {
return estStart;
}
public void setEstStart(Timestamp estStart) {
this.estStart = estStart;
}
public String getExpectedResults() {
return expectedResults;
}
public void setExpectedResults(String expectedResults) {
this.expectedResults = expectedResults;
}
public int getFolderId() {
return folderId;
}
public void setFolderId(int folderId) {
this.folderId = folderId;
}
public String getFunctionalAreaCode() {
return functionalAreaCode;
}
public void setFunctionalAreaCode(String functionalAreaCode) {
this.functionalAreaCode = functionalAreaCode;
}
public String getHowFoundCode() {
return howFoundCode;
}
public void setHowFoundCode(String howFoundCode) {
this.howFoundCode = howFoundCode;
}
public String getIssueCode() {
return issueCode;
}
public void setIssueCode(String issueCode) {
this.issueCode = issueCode;
}
public String getModuleCode() {
return moduleCode;
}
public void setModuleCode(String moduleCode) {
this.moduleCode = moduleCode;
}
public int getPctComplete() {
return pctComplete;
}
public void setPctComplete(int pctComplete) {
this.pctComplete = pctComplete;
}
public String getPriorityCode() {
return priorityCode;
}
public void setPriorityCode(String priorityCode) {
this.priorityCode = priorityCode;
}
public String getResolutionCode() {
return resolutionCode;
}
public void setResolutionCode(String resolutionCode) {
this.resolutionCode = resolutionCode;
}
public String getSeverityCode() {
return severityCode;
}
public void setSeverityCode(String severityCode) {
this.severityCode = severityCode;
}
public String getSoftwareVersionCode() {
return softwareVersionCode;
}
public void setSoftwareVersionCode(String softwareVersionCode) {
this.softwareVersionCode = softwareVersionCode;
}
public String getStepsToRepro() {
return stepsToRepro;
}
public void setStepsToRepro(String stepsToRepro) {
this.stepsToRepro = stepsToRepro;
}
}
With my current POJO, the JSON being spit out by Rest Assured looks like this:
{
"title": "Test",
"status": "New",
"actFinish": null,
"actHours": 0.0,
"actStart": null,
"actualResults": null,
"assigneeUserId": 0,
"customFields": [
"Test",
"test",
"tesT"
],
"id": "Test",
"name": "test",
"value": "tesT",
"description": null,
"estFinish": null,
"estHours": 0.0,
"estHrsRemaining": 0.0,
"estStart": null,
"expectedResults": null,
"folderId": 0,
"functionalAreaCode": null,
"howFoundCode": null,
"issueCode": null,
"moduleCode": null,
"pctComplete": 0,
"priorityCode": null,
"resolutionCode": null,
"severityCode": null,
"softwareVersionCode": null,
"stepsToRepro": null
}
My question is how do I write the the customFields such that it is nested correctly, as outlined in the sample JSON?
You need another POJO that represents a "CustomFields". For example:
public class CustomFields {
private String Id;
private String Name;
private String Value;
<getters and setters>
}
and use List<CustomFields> CustomFields instead of String[] customFields. Also note that your JSON example doesn't use camel case for the property names so your POJO shouldn't use camel case either.
There are ways to avoid using a POJO at all in REST Assured. You can for example use a HashMap instead which could be easier in some situations.

How to use get data using json object and display in listivew?

I have JSON like this
{
"data":
[
{
"id": 1,
"Name": "Choc Cake",
"Image": "1.jpg",
"Category": "Meal",
"Method": "",
"Ingredients":
[
{
"name": "1 Cup Ice"
},
{
"name": "1 Bag Beans"
}
]
},
{
"id": 2,
"Name": "Ice Cake",
"Image": "dfdsfdsfsdfdfdsf.jpg",
"Category": "Meal",
"Method": "",
"Ingredients":
[
{
"name": "1 Cup Ice"
}
]
}
]
}
I am using JSON Object to de-Serialize the data
this is what i am trying to
JSONObject jsonObj = new JSONObject(jsonStr);
String first = jsonObj.getJSONObject("data").getString("name");
System.out.println(first);
But a Cant seem to get the name or anything
Not sure what i am doing wrong?
and then i am trying to display it into a listview but haven't got to that part yet
data is a JSON Array, not a JSONObject
try: jsonObj.getJSONArray("data").getJSONObject(0).getString("name")
also note the difference between getString and optString, if you don't want an exception on null use the later.
First parse your Json from below method,
private ArrayList<String> getStringFromJson(String jsonStr)
{
ArrayList<String> mNames = new ArrayList<String>();
JSONArray array = new JSONArray(jsonStr);
for (int i = 0; i < array.length(); i++) {
JSONObject row = array.getJSONObject(i);
mNames= row.getString("Name");
}
return mNames;
}
try {
JSONObject jsonObj = new JSONObject(jsonStr);
jsonObj.getJSONArray("data").getJSONObject(0).getString("name")
} catch (JSONException e) {
}
Data is a json array. Use getJsonObject for json objects.
Refer to this example to create a ListView and populate it's adapter with data from a json object.
Use GSON instead JSON. Hope it helps you.
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
List<Data> datas= new ArrayList<Data>();
datas= Arrays.asList(gson.fromJson(jsonString, Data[].class));
public class Ingredients {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private String name;
}
public class Data {
private int id;
private String Name;
private String Image;
private String Category;
private String Method;
public List<Ingredients> getIngredients() {
return Ingredients;
}
public void setIngredients(List<Ingredients> ingredients) {
Ingredients = ingredients;
}
private List<Ingredients> Ingredients = new ArrayList<Ingredients>();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getImage() {
return Image;
}
public void setImage(String image) {
Image = image;
}
public String getCategory() {
return Category;
}
public void setCategory(String category) {
Category = category;
}
public String getMethod() {
return Method;
}
public void setMethod(String method) {
Method = method;
}
}

Java to json String ignore null values

I am creating this json string from the server as shown below and I was able to parse the string too. But when creating the json some fields like errormessage,createdDate,priority are null values. I dont want to show them in the string how can I do that?
Json Strin
{
"errormessage": null,
"createdDate": null,
"list": [{
"type": "app1",
"alternateId": "AlternateID",
"priority": null,
"description": "app for desc",
}],
"locationName": null,
"facilityManagerName": null,
"codeName": null,
"sourceKey": null,
"tablename": null,
"path": "list",
"service": "listserver",
"license": null,
"key": null,
}
expected String
{
"list": [{
"type": "app1",
"alternateId": "AlternateID",
"description": "app for desc",
}],
"path": "list",
"service": "listserver",
}
Generic Java Bean For creating the json:
public class AppObject<T> implements Serializable {
private String errormessage;
private Date createdDate;
private List<T> list;
private String locationName;
private String facilityManagerName;
private String codeName;
private Long sourceKey;
private String tablename;
private String path;
private String service;
private String license;
private Long key;
public AppObject() {
list = new ArrayList<T>();
}
public AppObject(List<T> list) {
this.list = list;
}
#XmlAnyElement(lax = true)
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
public String getLicense() {
return license;
}
public void setLicense(String license) {
this.license = license;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getService() {
return service;
}
public void setService(String service) {
this.service = service;
}
public String getTablename() {
return tablename;
}
public void setTablename(String tablename) {
this.tablename = tablename;
}
public String getErrormessage() {
return errormessage;
}
public void setErrormessage(String errormessage) {
this.errormessage = errormessage;
}
public Long getKey() {
return key;
}
public void setKey(Long key) {
this.key = key;
}
public String getLocationName() {
return locationName;
}
public void setLocationName(String locationName) {
this.locationName = locationName;
}
public String getFacilityManagerName() {
return facilityManagerName;
}
public void setFacilityManagerName(String facilityManagerName) {
this.facilityManagerName = facilityManagerName;
}
public Date getCreatedFeedFromDate() {
return createdFeedFromDate;
}
#JsonDeserialize(using = com.vxl.JsonDateDeserializer.class)
public void setCreatedFeedFromDate(Date createdFeedFromDate) {
this.createdFeedFromDate = createdFeedFromDate;
}
public Date getCreatedDate() {
return createdFeedToDate;
}
#JsonDeserialize(using = com.vxl.JsonDateDeserializer.class)
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
}
Honestly, I really wouldn't spend time on making a payload "look nice". Now if you said that you were motivated to keep the payload small for efficiency reasons I'd buy that.
Perhaps you use Jackson for serialising to JSON as well (I don't see why you are using two different libraries). I think that this question shows that Jackson's treatment of nulls can be controlled.
Change your get method. Set if(something!=null)return something; instead of return something;

Categories