Parsing array of object using Gson - java

My Rest service produces response as below
{
"feeds": [
{
"id": 672,
"imagePath": "http://pixyfi.com/uploads/image1.jpg",
"description": "Off White Cotton Net^The Dress Is Made From Cotton Net. It Is Stretchable And The Material Is Really Good. It Is A Bodycon Dress.",
"uploader": {
"id": 459,
},
"rejected": false,
"moderator": {
"id": 95,
},
"moderatedOn": "2016-12-19"
"imagePaths": [
"uploads/image1.jpg"
]
},
{
"id": 672,
"imagePath": "http://pixyfi.com/uploads/mage2.jpg",
"description": "Off White Cotton Net^The Dress Is Made From Cotton Net. It Is Stretchable And The Material Is Really Good. It Is A Bodycon Dress.",
"uploader": {
"id": 459,
},
"rejected": false,
"moderator": {
"id": 95,
},
"moderatedOn": "2016-12-19"
"imagePaths": [
"uploads/image2.jpg"
]
}
]
}
How can i parse it with Gson. IN my android client also i have same Feed Class witch which this JSON was generated.
Note: I have used Spring boot for my rest API and this JSON was generated with ResponseEntity.

Firstly, make sure that you have got valid JSON. The above in your case is not valid.
If a json object contains a single element, then there is no need to place comma after that. (comma after id in moderator and uploader object). You need to remove that.Also you need to place a comma after moderatedOn value.
Now after you got valid one, you have a feed class. In order to map your json feeds Array onto your List. You need to do the following.
Gson gson = new Gson();
Type feedsType = new TypeToken<ArrayList<Feed>>(){}.getType();
List<Feed> feedList = gson.fromJson(yourJsonResponseArray, feedsType);
Your Classes are must be like these.
Feed Class
public class Feed
{
private String id;
private String imagePath;
private Moderator moderator;
private String description;
private String rejected;
private Uploader uploader;
private String moderatedOn;
private String[] imagePaths;
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
public String getImagePath ()
{
return imagePath;
}
public void setImagePath (String imagePath)
{
this.imagePath = imagePath;
}
public Moderator getModerator ()
{
return moderator;
}
public void setModerator (Moderator moderator)
{
this.moderator = moderator;
}
public String getDescription ()
{
return description;
}
public void setDescription (String description)
{
this.description = description;
}
public String getRejected ()
{
return rejected;
}
public void setRejected (String rejected)
{
this.rejected = rejected;
}
public Uploader getUploader ()
{
return uploader;
}
public void setUploader (Uploader uploader)
{
this.uploader = uploader;
}
public String getModeratedOn ()
{
return moderatedOn;
}
public void setModeratedOn (String moderatedOn)
{
this.moderatedOn = moderatedOn;
}
public String[] getImagePaths ()
{
return imagePaths;
}
public void setImagePaths (String[] imagePaths)
{
this.imagePaths = imagePaths;
}
}
Moderator Class
public class Moderator
{
private String id;
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
}
Uploader Class
public class Uploader
{
private String id;
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
}

Related

How to merge two different Mono to produce final response in java reactive

In getProductById method I am trying to construct Mono<OrderResponse> from
Mono<Book> and Mono<Container> like shown below. The issue is response structure what this method is returning different from what I should get.
public Mono<OrderResponse> getProductById(Integer id) {
Mono<Book> monoBook=Mono.just(id).
flatMap(ops.service(BookingDomainService.class)::getProductById);
Mono<Container> monoCon=Mono.just(id).
flatMap(ops.service(BookingDomainService.class)::getContainerById);
OrderResponse or=new OrderResponse(monoBook,monoCon);
return Mono.just(or);
}
Structure of BOOK, Container and Response class are below.
My Book Class :
#Data
#AllArgsConstructor
#Builder
#NoArgsConstructor
public class Book implements Serializable {
#Id
private Integer id;
#Column
private String name;
#Column
private Long price;
}
Container Class:
public class Container {
private String containerName;
private String description;
public String getContainerName() {
return containerName;
}
public void setContainerName(String containerName) {
this.containerName = containerName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
My Response class:
public class OrderResponse {
private Mono<Book> orderMono;
private Mono<Container> orderContainerMono;
public Mono<Book> getOrderMono() {
return orderMono;
}
public void setOrderMono(Mono<Book> orderMono) {
this.orderMono = orderMono;
}
public Mono<Container> getOrderContainerMono() {
return orderContainerMono;
}
public void setOrderContainerMono(
Mono<Container> orderContainerMono) {
this.orderContainerMono = orderContainerMono;
}
public OrderResponse(Mono<Book> orderMono, Mono<Container> orderContainerMono) {
this.orderMono = orderMono;
this.orderContainerMono = orderContainerMono;
}
}
Final response that is being formed from method getProductById(Integer id) is
{
"orderMono": {
"scanAvailable": true
},
"orderContainerMono": {
"scanAvailable": true
}
}
but I need final response as:
I need final response as below json. How to achieve it.
Response:
{
"Book": {
"id": 12,
"name": "pn",
"price": 128
},
"Container": {
"containerName": " Cname",
"description": "diesc"
}
}
You can use Mono.zip to aggreate the results of multiple Monos into a single one that will be fulfilled when all of the given Monos have produced an item.
public final class OrderResponse {
private final Book book;
private final Container container;
public OrderResponse(Book book, Container container) {
this.book = book;
this.container = container;
}
// ...
}
public Mono<OrderResponse> getProductById(Integer id) {
// replace these lines with your actual calls
Mono<Book> bookMono = Mono.just(new Book(1, "Book 1", 1L));
Mono<Container> containerMono = Mono.just(new Container("A", "B"));
return Mono.zip(bookMono, containerMono)
.map(tuple -> new OrderResponse(tuple.getT1(), tuple.getT2()));
}
If you want to return a OrderResponse object directly instead of it being wrapped in a Mono, you can check out the Mono#block method.

response.body().getBasketShopList is empty, but API JSON in Postman is not empty

I am new to Android, it's about a week that I am spending 3 hours a day on this problem but still I can not find a solution, I am going to get a list of object from server and pass them to Adapter and another process. But I got into trouble, there is no error, in my Android Studio I got " response.code = 200 " but a list of my object is empty although in Postman with same authorization and same username a list of object is not empty. I don't know what should I do, so finally I forced to ask my question hear.
First let's take a look on Postman
Body : :
Authorization : :
Now when I clicked on Send Button in Postman I got "code: 200" and hear is the response Body:
{
"results": [
{
"_id": "5c7e69d283c0b00001108fad",
"count": 2,
"productId": "5ba51d877246b700016ec205",
"username": "rezash",
"createdAt": "2019-03-05T12:21:38.196UTC",
"updatedAt": "2019-03-05T12:36:11.058UTC",
"ACL": {
"*": {
"read": true,
"write": true
}
}
},
{
"_id": "5c7e69d483c0b00001108fae",
"count": 4,
"productId": "5acc0f2c790c0c000132c984",
"username": "rezash",
"createdAt": "2019-03-05T12:21:40.338UTC",
"updatedAt": "2019-03-05T12:36:15.830UTC",
"ACL": {
"*": {
"read": true,
"write": true
}
}
}
]
}
In my OnlineShopAPI Interface:
public interface OnlineShopAPI {
String BASE_URL = "https://api.backtory.com/";
#Headers("X-Backtory-Object-Storage-Id:5a154d2fe4b03ffa0436a535")
#HTTP(method = "POST" , path = "object-storage/classes/query/Basket" , hasBody = true)
Call<MainBasketShopResponse> mainBasketShop (
#Header("Authorization") String authorization,
#Body BasketShop basketShop
);
interface getMainBasketShop {
void onResponse(List<BasketShop> basketShopList);
void onFailure(String cause);
}
}
My MainBasketShopResponse class:
public class MainBasketShopResponse {
#SerializedName("results")
List<BasketShop> basketShopList;
public MainBasketShopResponse() {
}
public List<BasketShop> getBasketShopList() {
return basketShopList;
}
public void setBasketShopList(List<BasketShop> basketShopList) {
this.basketShopList = basketShopList;
}
}
BasketShop class:
public class BasketShop {
#SerializedName("username")
private String username;
#SerializedName("productId")
private String productId;
#SerializedName("count")
private float count;
#SerializedName("createdAt")
private String createdAt;
#SerializedName("_id")
private String id;
public String getCreatedAt() {
return createdAt;
}
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public BasketShop(String username) {
this.username = username;
}
public BasketShop() {
}
public BasketShop(String username, String productId, float count) {
this.username = username;
this.productId = productId;
this.count = count;
}
public BasketShop(String createdAt, String id) {
this.createdAt = createdAt;
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public float getCount() {
return count;
}
public void setCount(float count) {
this.count = count;
}
}
My Controller that contain retrofit:
public class MainBasketShopController {
OnlineShopAPI.getMainBasketShop getMainBasketShop;
public MainBasketShopController(OnlineShopAPI.getMainBasketShop getMainBasketShop) {
this.getMainBasketShop = getMainBasketShop;
}
public void start(String authorization , BasketShop basketShop){
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(OnlineShopAPI.BASE_URL)
.build();
OnlineShopAPI onlineShopAPI = retrofit.create(OnlineShopAPI.class);
Call<MainBasketShopResponse> call = onlineShopAPI.mainBasketShop(authorization , basketShop);
call.enqueue(new Callback<MainBasketShopResponse>() {
#Override
public void onResponse(Call<MainBasketShopResponse> call, Response<MainBasketShopResponse> response) {
if (response.isSuccessful()) {
Log.d("emptyhst1" , response.body().getBasketShopList().toString());
Log.d("emptyhst2" , Integer.toString(response.body().getBasketShopList().size()));
getMainBasketShop.onResponse(response.body().getBasketShopList());
}
}
#Override
public void onFailure(Call<MainBasketShopResponse> call, Throwable t) {
getMainBasketShop.onFailure(t.getMessage());
}
});
}
}
Hear is a part of my BasketShopFragment that I call MainBasketShopController with it:
MainBasketShopController mainBasketShopController = new MainBasketShopController(getMainBasketShop);
BasketShop basketShop = new BasketShop();
basketShop.setUsername(MyPreferenceManager.getInstance(getContext()).getUsername());
mainBasketShopController.start(
"bearer " + MyPreferenceManager.getInstance(getContext()).getAccessToken() ,
basketShop
);
OnlineShopAPI.getMainBasketShop getMainBasketShop = new OnlineShopAPI.getMainBasketShop() {
#Override
public void onResponse(List<BasketShop> basketShopList) {
Log.d("emptyhst3" , basketShopList.toString());
basketShopList2.clear();
basketShopList2.addAll(basketShopList);
mainBasketShopAdapter.notifyDataSetChanged();
}
#Override
public void onFailure(String cause) {
Toast.makeText(getContext(), cause , Toast.LENGTH_SHORT).show();
}
};
I checked both of username and accessToken that i passed to the controller and I am sure that everything is looking like in Postman
After a week I found a solution , I just changed a variable "float count" to "String count" from my Model(BasketShop Class) Ops!
#SerializedName("count")
private String count;

how to access to json with java

I have in a rest response this json:
{
"TRANS": {
"HPAY": [
{
"ID": "1234",
"DATE": "10/09/2011 18:09:27",
"REC": "wallet Ricaricato",
"COM": "Tasso Commissione",
"MSG": "Commento White Brand",
"STATUS": "3",
"EXTRA": {
"IS3DS": "0",
"CTRY": "FRA",
"AUTH": "455622"
},
"INT_MSG": "05-00-05 ERR_PSP_REFUSED",
"MLABEL": "IBAN",
"TYPE": "1"
}
]
}
}
I have made pojo class to map this json in java.
public class Trans {
private List<Hpay> hpay;
public Trans(){
}
//getter and setter
}
public class Hpay {
private String id;
private String date;
private String com;
private String msg;
private String status;
private List<Extra> extra;
private String int_msg;
private String mlabel;
private String type;
public Hpay(){
}
//getter and setter
}
I try to map the object with Gson library.
Gson gson=new Gson();
Trans transaction=gson.fromJson(response.toString(), Trans.class);
If i call hpay method on transaction i have null..i don't know why...
I have deleted previous answer and add new one as par your requirement
JSON String :
{
"TRANS": {
"HPAY": [{
"ID": "1234",
"DATE": "10/09/2011 18:09:27",
"REC": "wallet Ricaricato",
"COM": "Tasso Commissione",
"MSG": "Commento White Brand",
"STATUS": "3",
"EXTRA": {
"IS3DS": "0",
"CTRY": "FRA",
"AUTH": "455622"
},
"INT_MSG": "05-00-05 ERR_PSP_REFUSED",
"MLABEL": "IBAN",
"TYPE": "1"
}
]
}
}
Java Objects : (Here Extra is not list)
public class MyObject {
#SerializedName("TRANS")
#Expose
private Trans trans;
public Trans getTRANS() {return trans;}
public void setTRANS(Trans trans) {this.trans = trans;}
}
public class Trans {
#SerializedName("HPAY")
#Expose
private List<HPay> hPay;
public List<HPay> getHPAY() {return hPay;}
public void setHPAY(List<HPay> hPay) {this.hPay = hPay;}
}
public class HPay {
#SerializedName("ID")
#Expose
private String id;
#SerializedName("DATE")
#Expose
private String date;
#SerializedName("REC")
#Expose
private String rec;
#SerializedName("COM")
#Expose
private String com;
#SerializedName("MSG")
#Expose
private String msg;
#SerializedName("STATUS")
#Expose
private String status;
#SerializedName("EXTRA")
#Expose
private Extra extra;
#SerializedName("INT_MSG")
#Expose
private String intMsg;
#SerializedName("MLABEL")
#Expose
private String mLabel;
#SerializedName("TYPE")
#Expose
private String type;
public String getID() {return id;}
public void setID(String id) {this.id = id;}
public String getDATE() {return date;}
public void setDATE(String date) {this.date = date;}
public String getREC() {return rec;}
public void setREC(String rec) {this.rec = rec;}
public String getCOM() {return com;}
public void setCOM(String com) {this.com = com;}
public String getMSG() {return msg;}
public void setMSG(String msg) {this.msg = msg;}
public String getSTATUS() {return status;}
public void setSTATUS(String status) {this.status = status;}
public Extra getEXTRA() {return extra;}
public void setEXTRA(Extra extra) {this.extra = extra;}
public String getINTMSG() {return intMsg;}
public void setINTMSG(String intMsg) {this.intMsg = intMsg;}
public String getMLABEL() {return mLabel;}
public void setMLABEL(String mLabel) {this.mLabel = mLabel;}
public String getTYPE() {return type;}
public void setTYPE(String type) {this.type = type;}
}
public class Extra {
#SerializedName("IS3DS")
#Expose
private String is3ds;
#SerializedName("CTRY")
#Expose
private String ctry;
#SerializedName("AUTH")
#Expose
private String auth;
public String getIS3DS() { return is3ds; }
public void setIS3DS(String is3ds) { this.is3ds = is3ds; }
public String getCTRY() { return ctry; }
public void setCTRY(String ctry) { this.ctry = ctry; }
public String getAUTH() { return auth; }
public void setAUTH(String auth) { this.auth = auth; }
}
Conversion Logic :
import com.google.gson.Gson;
public class NewClass {
public static void main(String[] args) {
Gson g = new Gson();
g.fromJson(json, MyObject.class);
}
static String json = "{ \"TRANS\": { \"HPAY\": [{ \"ID\": \"1234\", \"DATE\": \"10/09/2011 18:09:27\", \"REC\": \"wallet Ricaricato\", \"COM\": \"Tasso Commissione\", \"MSG\": \"Commento White Brand\", \"STATUS\": \"3\", \"EXTRA\": { \"IS3DS\": \"0\", \"CTRY\": \"FRA\", \"AUTH\": \"455622\" }, \"INT_MSG\": \"05-00-05 ERR_PSP_REFUSED\", \"MLABEL\": \"IBAN\", \"TYPE\": \"1\" } ] } }";
}
Here I use Google Gosn lib for conversion.
And need to import bellow classes for annotation
com.google.gson.annotations.Expose;
com.google.gson.annotations.SerializedName;
First parse the json data using json.simple and then set the values using setters
Object obj = parser.parse(new FileReader( "file.json" ));
JSONObject jsonObject = (JSONObject) obj;
JSONArray hpayObj= (JSONArray) jsonObject.get("HPAY");
//get the first element of array
JSONObject details= hpayObj.getJSONArray(0);
String id = (String)details.get("ID");
//set the value of the id field in the setter of class Trans
new Trans().setId(id);
new Trans().setDate((String)details.get("DATE"));
new Trans().setRec((String)details.get("REC"));
and so on..
//get the second array element
JSONObject intMsgObj= hpayObj.getJSONArray(1);
new Trans().setIntmsg((String)details.get("INT_MSG"));
//get the third array element
JSONObject mlabelObj= hpayObj.getJSONArray(2);
new Trans().setMlabel((String)details.get("MLABEL"));
JSONObject typeObj= hpayObj.getJSONArray(3);
new Trans().setType((String)details.get("TYPE"));
Now you can get the values using your getter methods.

JSON to POJO with Integer as Array attribute key Name

I have the following json which has a product array with product_id as each array.Product ids are numbers. When I am looking online for the pojo classes I am getting Class names which starts with digits which is not allowed.
{
"_id:" : "1234AG567",
"products" : {
"1234":{
"product_name" : "xyz",
"product_type" : "abc"
},
"3456":{
"product_name" : "zzz",
"product_type" : "def"
}
}
}
Below are the Pojo classes I am getting
public class MyPojo
{
private Products products;
public Products getProducts ()
{
return products;
}
public void setProducts (Products products)
{
this.products = products;
}
#Override
public String toString()
{
return "ClassPojo [products = "+products+"]";
}
}
public class Products
{
private 1234 1234;
private 3456 3456;
public 1234 get1234 ()
{
return 1234;
}
public void set1234 (1234 1234)
{
this.1234 = 1234;
}
public 3456 get3456 ()
{
return 3456;
}
public void set3456 (3456 3456)
{
this.3456 = 3456;
}
#Override
public String toString()
{
return "ClassPojo [1234 = "+1234+", 3456 = "+3456+"]";
}
}
public class 3456
{
private String product_name;
private String product_type;
public String getProduct_name ()
{
return product_name;
}
public void setProduct_name (String product_name)
{
this.product_name = product_name;
}
public String getProduct_type ()
{
return product_type;
}
public void setProduct_type (String product_type)
{
this.product_type = product_type;
}
#Override
public String toString()
{
return "ClassPojo [product_name = "+product_name+", product_type = "+product_type+"]";
}
}
public class 1234
{
private String product_name;
private String product_type;
public String getProduct_name ()
{
return product_name;
}
public void setProduct_name (String product_name)
{
this.product_name = product_name;
}
public String getProduct_type ()
{
return product_type;
}
public void setProduct_type (String product_type)
{
this.product_type = product_type;
}
#Override
public String toString()
{
return "ClassPojo [product_name = "+product_name+", product_type = "+product_type+"]";
}
}
I have used the http://pojo.sodhanalibrary.com/ to convert
Any help how to create pojo for this JSON is welcome. Thanks in advance.
You can use Map to store the products and wrap it in another class to store the whole json. E.g. Product class would look like this:
class Product {
#JsonProperty("product_name")
private String productName;
#JsonProperty("product_type")
private String productType;
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getProductType() {
return productType;
}
public void setProductType(String productType) {
this.productType = productType;
}
}
Wrapper class would look like this:
class ProductList{
#JsonProperty("_id")
private String id;
private Map<String, Product> products;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Map<String, Product> getProducts() {
return products;
}
public void setProducts(Map<String, Product> products) {
this.products = products;
}
}
Here's is the deserialization example with Jackson:
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
ProductList list = mapper.readValue("{\"_id\" : \"1234AG567\",\"products\" : {\"1234\":{\"product_name\" : \"xyz\",\"product_type\" : \"abc\"},\"3456\":{\"product_name\" : \"zzz\",\"product_type\" : \"def\"}}}", ProductList.class);
System.out.println(list.getId());
System.out.println(list.getProducts());
}
Please note that your json has a typo in it. Id field should be _id and not _id: (if that is the actual field name then you can change JsonProperty annotation to _id:.
Here is documentation for Jackson.
The JSON is valid, but you WILL NOT be able to create POJOs to represent that. Like you have already seen, you cannot create classes that begin with numbers, and you don't want to do this anyway as they won't provide any meaning to you.
I'm going to guess that products is an array of Product, and that number is an ID or something. The JSON should look something like this:
{
"products": [
{
"id": "1234",
"product_name": "xyz",
"product_type": "abc"
},
{
"id": "3456",
"product_name": "zzz",
"product_type": "def"
}]
}
Which would deserialize into a class that contains
private List<Product> products;
assuming that that the Product class looks like
class Product {
private Integer id;
#JsonProperty(value = "product_name")
private String productName;
#JsonProperty(value = "product_type")
private String productType;
}

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.

Categories