Invoking a rest api client - java

I have created a rest api in eclipse as a maven project.
MobileAnalyticsModel class for rest api is
package org.subhayya.amazonws.mobileanalytics;
import java.util.Date;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class MobileAnalyticsModel {
private String name;
private Date created;
private String location;
private String prize;
private String requirement;
public MobileAnalyticsModel() {
}
public MobileAnalyticsModel(String name, String location, String prize, String requirement) {
this.name = name;
this.location = location;
this.prize = prize;
this.requirement = requirement;
this.created = new Date();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getPrize() {
return prize;
}
public void setPrize(String prize) {
this.prize = prize;
}
public String getRequirement() {
return requirement;
}
public void setRequirement(String requirement) {
this.requirement = requirement;
}
}
this is the json response of the created api:
and
this is my sample test code for invoking rest api:
package org.subhayya.example;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.MediaType;
public class SampleTestREstClient {
public static void main(String[] args) {
Client client = ClientBuilder.newClient( );
String reponse = client.target("http://localhost:8080/AgentBasedCloudServiceCompositionFramework/webapi/mobileanalytics/mobileanalyticsjson")
.request(MediaType.APPLICATION_JSON)
.get(String.class);
System.out.println(reponse);
}}
then i got full json response.. as
[{"created":"2017-03-30T14:36:58.56","location":"http://api.server.com","name":"Mobile Analytics","prize":"$1.00 per 1,000,000 Amazon Mobile Analytics events per month thereafter","requirement":"PutEvents"}]
But I want to have the single parameter as my output, for e.g., name, location or requirement.I am creating client invoking code also in the same maven project. So I wrote my code as below
Client client = ClientBuilder.newClient( );
MobileAnalyticsModel reponse =
client.target("http://localhost:8080/AgentBasedCloudServiceCompositionFramework/webapi/mobileanalytics/mobileanalyticsjson")
.request(MediaType.APPLICATION_JSON)
.get(MobileAnalyticsModel.class);
System.out.println(reponse.getName());
But I am getting exception, So I changed it to System.out.println(reponse);
) get atleast JSON response, then also getting error.
how do I get single name parameter from the JSON response? I am new to this rest api..please help me to fix this as soon as possible.thanks in advance

Your response is a string. The simplest way to access elements of your JSON-response is to convert the resonse to a Json-Object. Then you can access the fields easily by their name.
Have a look at:
How to parse JSON in Java

You can also check the below link to convert json to object.
Parse a JSON response as an object

This code works for me..
String url = "http://localhost:8080/AgentBasedCloudServiceCompositionFramework/webapi/mobileanalytics/";
String city = "mobileanalyticsjson";
Client client = ClientBuilder.newClient();
WebTarget webTarget = client.register(JsonProcessingFeature.class).target(url);
JsonArray jsonArray = webTarget.path(city)
.request(MediaType.APPLICATION_JSON_TYPE).get(JsonArray.class);
for (JsonObject jsonObject : jsonArray.getValuesAs(JsonObject.class)) {
System.out.println(jsonObject.getString("name"));
System.out.println(jsonObject.getString("location")); }

Related

Java RESTful returning Object inside of an object, takes it's toString instead of converting to JSON

(NOTE: I am sorry if the layout of this post isn't the best, I've
spent quite a lot of time figuring the features of this editor)
Hi, I am doing a RESTful web project and I run into a problem returning an object that contains another object (But the object inside is literally an "Object").
In my case I have a Company, Customer and Coupon resources. Each one of then contains fields, #XMLRootElement annotation in the class level, an empty constructor (along with constructors that receives the arguments) and of course, the getters and setters.
As for the service, there are annotations in the class level:
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
And the get method it's self:
#GET
#Path("/myCompany)
public Message getMyCompany(){
Message message;
try{
message = new MessageSuccess(company);
} catch(Exception e){
message = new MessageError(e.getMessage());
}
return message;
}
Now the way Message object is built, it's an abstract class (that contains the #XMLRootElement as well) it has three fields:
messageType (enum)
value (Object)
message (String)
it has all the features of the resource (getters and setters, construction, etc...)
And there are two classes that extending the Message.
they aswell have an empty constructor and parameterized one, they don't have the #XMLRootElement annotations.
Now the problem is, when ever the client does the get method, it receives a JSON object that has
messageType: 'SUCCESS'
value: 'com.publicCodes.resources.Company#6c4sad546d'
Basically it returns a toString() of the Company object.
I have no clue how to fix that.
Returning servlet's Response object is not an option due to a bad practice.
Returning the Company object it's self is as well not an option.
Thanks and waiting for your solutions!
**
EDIT for those who wanna see the actual code:
**
Here is the Message abstract class:
package com.publicCouponRest.util;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSeeAlso;
#XmlRootElement
public abstract class Message {
private MessageResultType messageType;
private Object value;
private String message;
public Message() {
}
public Message(MessageResultType messageType, String message) {
this.messageType = messageType;
this.message = message;
}
public Message(MessageResultType messageType, Object value) {
this.messageType = messageType;
this.value = value;
}
public MessageResultType getMessageType() {
return messageType;
}
public void setMessageType(MessageResultType messageType) {
this.messageType = messageType;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
And here is MessageSuccess that extends Message:
package com.publicCouponRest.util;
public class MessageSuccess extends Message {
public MessageSuccess() {
}
public MessageSuccess(Object value) {
super(MessageResultType.SUCCESS, value);
}
}
and of course Company resource:
package com.publicCodes.resources;
import java.util.Map;
import javax.xml.bind.annotation.XmlRootElement;
import com.publicCouponRest.services.AttributeKeys;
#XmlRootElement
public class Company {
private long id;
private String compName;
private String password;
private String email;
private Map<Long, Coupon> coupons;
private CompanyStatus companyStatus;
private AttributeKeys userType = AttributeKeys.COMPANY;
public Company(long id, String compName, String password, String email, Map<Long, Coupon> coupons, CompanyStatus companyStatus) {
this(compName, password, email);
this.id = id;
this.coupons = coupons;
this.companyStatus = companyStatus;
}
public Company(String compName, String password, String email) {
super();
this.compName = compName;
this.password = password;
this.email = email;
}
public Company() {
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getCompName() {
return compName;
}
public void setCompName(String compName) {
this.compName = compName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Map<Long, Coupon> getCoupons() {
return coupons;
}
public CompanyStatus getCompanyStatus() {
return companyStatus;
}
public void setCompanyStatus(CompanyStatus companyStatus) {
this.companyStatus = companyStatus;
}
public void setCoupons(Map<Long, Coupon> coupons) {
this.coupons = coupons;
}
public AttributeKeys getUserType() {
return userType;
}
public void setUserType(AttributeKeys userType) {
this.userType = userType;
}
}
Ok. I think that you are having too much fun with jackson:
You are trying to put 'whatever object' in a node. aren't you?
To do that you must use the annotation:
#XmlAnyElement(lax=false)
so something like:
#XmlAccessorType(XmlAccessType.FIELD)
#XmlRootElement
public abstract class Message {
....
#XmlAnyElement(lax=false)
private Object value;
....
Should be necessary. This way you will be able to put whatever incoming XML data node in that Object (JAXB will have to know the class of that Object and that class must be annotated, but it let you manage an undetermined class)
Also (EDITED):
In the other way: Object-> XML: The problem now is that you are sending to JAXB your 'Company' object but it only sees an 'Object' because you are telling it that it's an object of type 'Object', and JAXB only know how to serialize an 'Object.class' calling to it's .toString() because Object.class hasn't got any JAXB annotation. Try returning, instead of the object, the result of this method:
(Data will be your response and clazz Company.class or whatever)
import javax.xml.bind.JAXBContext;
import javax.xml.transform.dom.DOMResult;
import org.w3c.dom.Element;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
...
public static Element marshallToElement(Object data, Class clazz) {
DOMResult res = null;
try {
JAXBContext ctx = JAXBContextManager.getInstance(clazz.getPackage().getName());
Marshaller marshaller = ctx.createMarshaller();
res = new DOMResult();
marshaller.marshal(data, res);
} catch (JAXBException e) {
LOG.error(e);
}
return ((Document)res.getNode()).getDocumentElement();
}
This way you will return a JAXBElement, which is a 'bunch of nodes' that JAXB will know how to marshall.
At this point, if it works for you, it's a good practice caching the JAXBContext, it can be do saffely (JAXBContext is thread-safe, Marshallers NO) and it's a heavy duty for JAXB to execute that:
JAXBContextManager.getInstance(clazz.getPackage().getName())
So try to do it only once for each transformation.
PS:
Try putting JAXB annotations only in final classes, I'd had problems with that (because I was using annotations in an annotated subclass... And finally is cleaner to have all annotations in the same class)
Jersey/JAX-RS 2 client
I consider you read a bit of WebTarget API, how it works and what it returns. And Also return a Response Object
And then you can change your method to this:
#GET
#Path("/myCompany)
public Response getMyCompany() {
Message message;
try {
message = new MessageSuccess(company);
return Response.status(200).entity(message).build();
} catch (Exception e) {
message = new MessageError(e.getMessage());
return Response.status(500).entity(message).build();
}
}
After that you should add this to your main method:
WebTarget target = client.target(BASE).path("myCompany");
Response response = target.request().accept(...).post(Entity.json(message));//modify this line to suit your needs
Message message = response.readEntity(Message.class);
Have tried similar thing before and I got my help from #peeskillet's answer on this stackoverflow page.
Hope it did be of Help,thank you.

how to upload file and save file in db use spring boot and jpa?

I am new in spring boot.I wanna upload a small file use spring boot and save it in db use jpa.
But I don't have good resolution.
My program like these:
database table:
CREATE TABLE `report` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`logo` BLOB NOT NULL,
`created_time` int(10) NOT NULL,
`updated_time` int(10) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8
jpa bean:
Report.java
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Lob;
import javax.persistence.Table;
import java.io.Serializable;
#Entity
#Table(name="mf_report")
public class Report implements Serializable{
#Column(name="id")
private int id;
#Column(name="name")
private String name;
#Lob
#Column(name="logo", length=100000)
private byte[] logo;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public byte[] getLogo() {
return logo;
}
public void setLogo(byte[] logo) {
this.logo = logo;
}
}
ReportReposity.java:
#Repository
public interface ReportRepository extends CrudRepository<Report,Long>{
}
ReportService.java:
#Service
public class ReportService extends CrudService<Report, ReportRepository> {
private final static Logger logger = LoggerFactory.getLogger(ReportService.class);
#Override
#Autowired
public void setRepo(ReportRepository repo) {
this.repo = repo;
}
#Override
public Report copy(Report from, Report to) {
to = from;
return to;
}
#Autowired
private ReportRepository reportRepository;
public boolean saveReportByRequestBean(ReportAddQueryRequest reportBeanQueryRequest){
try {
Report report = new Report();
report.setName(reportBeanQueryRequest.getName());
report.setLogo(reportBeanQueryRequest.getLogo());
long now = System.currentTimeMillis()/1000;
report.setCreateTime(now);
report.setUpdateTime(now);
this.save(report);
}catch (Exception e){
logger.error("save report error:", e);
return false;
}
return true;
}
}
ReportParamBean.java:
import org.hibernate.validator.constraints.NotEmpty;
import java.io.Serializable;
public class ReportParamBean extends AbsRequest implements Serializable {
private long reportId;
#NotEmpty(message = "Param 'name' can't be NULL")
private String name;
private String logo;// In fact, I don't know what type should logo be, File or ?
}
AbsRequest.java:
public class AbsRequest implements Serializable {
private static final long serialVersionUID = -8928786145900600868L;
#NotEmpty(message = "Param 'token' can't be NULL")
#NotNull
private String token;
#NotEmpty(message = "Param 'sign' can't be NULL")
private String sign;
#Min(value = 1, message = "Param 'time' is invalid")
private Long time;
#Min(value = -1, message = "Param 'nodeId' is invalid")
#NotNull(message = "Param 'nodeId' can't be NULL")
private Long nodeId;
private String nodeName;
#Override
public String toString() {
return new ToStringBuilder(this)
.append("token", token)
.append("sign", sign)
.append("time", time)
.append("nodeId", nodeId)
.append("nodeName", nodeName)
.toString();
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getSign() {
return sign;
}
public void setSign(String sign) {
this.sign = sign;
}
public Long getTime() {
return time;
}
public void setTime(Long time) {
this.time = time;
}
public Long getNodeId() {
return nodeId;
}
public void setNodeId(Long nodeId) {
this.nodeId = nodeId;
}
public String getNodeName() {
return nodeName;
}
public void setNodeName(String nodeName) {
this.nodeName = nodeName;
}
}
ReportController.java:
#RestController
#RequestMapping("/api")
public class ReportController {
#Autowired
private ReportService reportService;
#RequestMapping(value = "/report", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
public JSONObject createReport(#RequestBody ReportAddQueryRequest reportBeanQueryRequest){
boolean result = reportService.saveReportByRequestBean(reportBeanQueryRequest);
if (!result){
return ResponseWrapper.buildResponse(RTCodeEnum.C_SERVICE_NOT_AVAILABLE, "add report failed");
}
return ResponseWrapper.buildResponse(RTCodeEnum.C_OK, "add report success");
}
}
I don't know whether I can post a file and other params to server in just one post request,then save the data in db.Could you give me resolution.
Special thanks.
Use Spring's multipart file. In simple implementation you can then get InputStream from it, read the content of the file (being saved on hdd) to a byte array and save it to database.
Consider up voting if this answer help you.
suppose you want to upload a file's data to database then you could do it in two steps:
upload your file as multipart file in your controller class.
#PostMapping("/uploadYourFile")
public String uploadFile( MultipartFile file) throws IOException {
FileInputStream inputStream = (FileInputStream) file.getInputStream();
//you can use inputStream object which currently has your "file" data
// you can process this to fetch your data.
return "file uploaded successfully ";
}
Read your uploaded file"inputStream" fetch the data and insert it into your DB through your db query
I have made an app to upload, download and delete files to/from database using Spring Boot Rest APIs. I also used Spring Web MultipartFile interface to handle HTTP multi-part requests.
Source code: https://github.com/OusamaELIDRISSI/upload-files-database
Happy coding 🙂

Java Spring REST API Status 400 response on POST / PUT

I built a REST API Service using Java Spring Cloud / Boot. Firstly, I made a simple class connected to a MongoDB and a controller with service that should allow me to add, delete, update and get all the objects. When using POSTMAN these all work, however when I want to add or update an object using redux and fetch API I get a status 400 and "bad request" error. This seems to have something to do with the JSON I'm sending in the body but it is the exact same format of JSON that is working with for example POSTMAN.
My action in Redux. For simplicity / test purposes I added an object at the top in stead of using the object being sent from the page.
var assetObject = {
"vendor" : "why dis no work?",
"name": "wtf",
"version": "231",
"category" : "qsd",
"technology" : "whatever"
}
export function addAsset(access_token, asset) {
return dispatch => {
fetch(constants.SERVER_ADDRESS + '/as/asset/add',
{
method: 'POST',
credentials: 'include',
headers: {
'Authorization': 'Bearer' + access_token,
'Content-Type': 'application/json'
},
body: assetObject
})
.then(res => dispatch({
type: constants.ADD_ASSET,
asset
}))
}
}
Controller code in Java Spring:
#RequestMapping(method = RequestMethod.POST, path = "/add")
public void addAsset(#RequestBody Asset asset) {
assetService.addAsset(asset);
}
Status ok while doing it in postman:
The error I get when using Redux / Fetch API (I only removed the directory structure because it has company name in it):
Have been stuck on this for a while, any help is much appreciated!
EDIT Asset Object:
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Document(collection = "assets")
public class Asset {
#Id
private String id;
private String vendor;
private String name;
private String version;
private String category;
private String technology;
public Asset() {
}
public Asset(String id,
String vendor,
String name,
String version,
String category,
String technology) {
this.id = id;
this.vendor = vendor;
this.name = name;
this.version = version;
this.category = category;
this.technology = technology;
}
public String getId() {
return id;
}
public String getVendor() {
return vendor;
}
public String getName() {
return name;
}
public String getVersion() {
return version;
}
public String getCategory() {
return category;
}
public String getTechnology() {
return technology;
}
public void setId(String id) {
this.id = id;
}
public void setVendor(String vendor) {
this.vendor = vendor;
}
public void setName(String name) {
this.name = name;
}
public void setVersion(String version) {
this.version = version;
}
public void setCategory(String category) {
this.category = category;
}
public void setTechnology(String technology) {
this.technology = technology;
}
}
your error message says :
; required request body is missing
i think the error happens when your controller method
trying to form an object from the incoming request.
when you are sending the request you have to set each and every field related to the object.
if you are planning on not setting a property you should mark that field with #JsonIgnore annotation.
you can use #JsonIgnore annotation on the variable which will ignore this property
when forming the object as well as when outputing the object.
use #JsonIgnore annotation on the setter method , which i think you should do now since
you are ignoring the id property when making the request.
#JsonIgnore
public void setId(String id) {
this.id = id;
}
and you can return httpstatus code from the controller method,
so that client knows request was successful
#ResponseBody
public ResponseEntity<String> addAsset(#RequestBody Asset asset) {
return new ResponseEntity<String>("your response here", HttpStatus.OK);
}

Sending java object to c# web service

I am working on one project in which i am developing a java client for .NET/C#.
I want to send information of device to the web service.
I have created one class which contains the device information.
I want to send the information of the device to service.
what is appropriate way to do this. Please help.
sorry for my weak English.
And thanks in advance.
package com.ivb.syntecApp.models;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class DeviceInformation {
private String vendorId;
private String productId;
private String hardwareRevision;
private String deviceName;
private String manufacturerName;
#XmlElement
public String getVendorId() {
return vendorId;
}
public void setVendorId(String vendorId) {
this.vendorId = vendorId;
}
#XmlElement
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
#XmlElement
public String getHardwareRevision() {
return hardwareRevision;
}
public void setHardwareRevision(String hardwareRevision) {
this.hardwareRevision = hardwareRevision;
}
#XmlElement
public String getDeviceName() {
return deviceName;
}
public void setDeviceName(String deviceName) {
this.deviceName = deviceName;
}
#XmlElement
public String getManufacturerName() {
return manufacturerName;
}
public void setManufacturerName(String manufacturerName) {
this.manufacturerName = manufacturerName;
}
}
For this purpose the Common Object Request Broker Architecture (CORBA) was developed. But it's too big gun for your needs. I recommend you to use some kind of REST or SOAP service with transformators(Adapter pattern)
I have solved at my own. I don't know is it good practice or not.
My answer is ->
I have used JAXB for marshaling DeviceInformation class and used
`void marshal(Object jaxbElement,
Writer writer)
throws JAXBException
` to convert this object in to StringWriter object then converted it into string and sent this string to .NET/C# service.
This meets my requirement.
I found this here

Getting an error when trying to deserialize a JSON string with GSON

I'm trying to decode a JSON string that's coming from a php script I made that gets results out of my MySQL database. It returns a JSON array.
This is the code for my decoder:
package com.github.viperdream;
import java.lang.reflect.Type;
import java.util.List;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class JSONDecoder {
public static void decodePin(String data){
Gson gson = new Gson();
Type type = new TypeToken<List<Pin>>(){}.getType();
List<Pin> pin = gson.fromJson(data, type);
for (Pin newPin : pin){
Log.d("GSON", newPin.getPinTitle());
}
}
}
This is the Pin object class:
package com.github.viperdream;
public class Pin {
private Integer pinID;
private String pinTitle;
private String pinMessage;
private Integer pinDuration;
private Float pinX;
private Float pinY;
private String pinColor;
private String author;
private Integer pinSQLId;
public Pin(){}
public Pin(int pinID, String pinTitle, String pinMessage, Integer pinDuration, Float pinX, Float pinY, String pinColor, String author, Integer pinSQLId){
this.pinID = pinID;
this.pinTitle = pinTitle;
this.pinMessage = pinMessage;
this.pinDuration = pinDuration;
this.pinX = pinX;
this.pinY = pinY;
this.pinColor = pinColor;
this.author = author;
this.pinSQLId = pinSQLId;
}
public Pin(String pinTitle, String pinMessage, Integer pinDuration, Float pinX, Float pinY, String pinColor, String author, Integer pinSQLId){
this.pinTitle = pinTitle;
this.pinMessage = pinMessage;
this.pinDuration = pinDuration;
this.pinX = pinX;
this.pinY = pinY;
this.pinColor = pinColor;
this.author = author;
this.pinSQLId = pinSQLId;
}
//get ------------------------------------------------------
public int getID(){
return this.pinID;
}
public String getPinTitle(){
return this.pinTitle;
}
public String getPinMessage(){
return this.pinMessage;
}
public Integer getPinDuration(){
return this.pinDuration;
}
public Float getPinX(){
return this.pinX;
}
public Float getPinY(){
return this.pinY;
}
public String getPinColor(){
return this.pinColor;
}
public String getPinAuthor(){
return this.author;
}
public Integer getPinSQLId(){
return this.pinSQLId;
}
//set ------------------------------------------------------
public void setPinID(int pinID){
this.pinID = pinID;
}
public void setPinTitle(String pinTitle){
this.pinTitle = pinTitle;
}
public void setPinMessage(String pinMessage){
this.pinMessage = pinMessage;
}
public void setPinDuration(int pinDuration){
this.pinDuration = pinDuration;
}
public void setPinX(Float pinX){
this.pinX = pinX;
}
public void setPinY(Float pinY){
this.pinY = pinY;
}
public void setPinColor(String pinColor){
this.pinColor = pinColor;
}
public void setPinAuthor(String author){
this.author = author;
}
public void setPinSQLId(Integer pinSQLId){
this.pinSQLId = pinSQLId;
}
}
This is the JSON String that I'm trying to decode:
[
{
"id":"2",
"title":"test1",
"message":"test2",
"duration":"1",
"x":"125",
"y":"754.5",
"color":"red",
"author":"viperdream"
},
{
"id":"3",
"title":"looking for someone",
"message":"i need to go now",
"duration":"1",
"x":"401",
"y":"472.5",
"color":"red",
"author":"viperdream"
},
{
"id":"4",
"title":"test3",
"message":"testing:)",
"duration":"1",
"x":"195",
"y":"512.5",
"color":"red",
"author":"viperdream"
}
]
And this is how I make the Json string in PHP
while($pin = mysql_fetch_assoc($query_exec)) {
$pins[] = $pin;
}
echo json_encode($pins);
Whenever I run my app, it gives me this error:
java.lang.NullPointerException: println needs a message
Anyone knows what I am doing wrong?
If you need any more information, please do ask!
Thanks in advance!
Gson tries to match the JSON element names to your class' field names. In your case, you have id, title, etc. instead of pinId, pinTitle, etc. If Gson finds an element for which it doesn't find a matching field, it skips it, leaving the field null (or whatever default it has).
The element and field names need to be equal.
Alternatively, you could annotate your field with #SerializedName and give it the value you are expecting from the json.
#SerializedName("id")
private Integer pinID;

Categories

Resources