I have a model NewsFeedItem like this:
public class NewsFeedItem {
#PropertyName("like_number")
protected int likeCount = 0;
#PropertyName("time")
protected long timestamp;
#PropertyName("ownerUid")
protected String ownerUid;
#PropertyName("ownerUsername")
protected String ownerUsername;
#PropertyName("comments")
protected List<Comment> comments;
#PropertyName("likes")
protected Set<String> likes; //Store user uid of who like this status
public NewsFeedItem() {
}
protected NewsFeedItem(int likeCount, long timestamp, String ownerUid, String ownerUsername, List<Comment> comments, Set<String> likes) {
this.ownerUid = ownerUid;
this.ownerUsername = ownerUsername;
this.likeCount = likeCount;
this.timestamp = timestamp;
this.comments = comments;
this.likes = likes;
}
public int getLikeCount() {
return likeCount;
}
public void setLikeCount(int likeCount) {
this.likeCount = likeCount;
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
public String getOwnerUid() {
return ownerUid;
}
public void setOwnerUid(String ownerUid) {
this.ownerUid = ownerUid;
}
public String getOwnerUsername() {
return ownerUsername;
}
public void setOwnerUsername(String ownerUsername) {
this.ownerUsername = ownerUsername;
}
public List<Comment> getComments() {
return comments;
}
public void setComments(List<Comment> comments) {
this.comments = comments;
}
public Set<String> getLikes() {
return likes;
}
public void setLikes(Set<String> likes) {
this.likes = likes;
}
}
Then I subclass it in Status model:
#IgnoreExtraProperties
public class Status extends NewsFeedItem {
#PropertyName("content")
protected String content;
#PropertyName("photo")
protected String photoUrl;
public Status() {
//Required for deserialize
}
public Status(String ownerUid, String ownerUsername, String content, String photoUrl, int likeCount, long timestamp, List<Comment> comments, Set<String> likes) {
super(likeCount, timestamp, ownerUid, ownerUsername, comments, likes);
this.content = content;
this.photoUrl = photoUrl;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getPhotoUrl() {
return photoUrl;
}
public void setPhotoUrl(String photoUrl) {
this.photoUrl = photoUrl;
}
}
The code pushing data to Firebase:
#Override
public void pushStatusToFirebase(Status status) {
database.getReference("status").push().setValue(status);
}
But when I push to Firebase the like_number and likeCount display together like this:
It also happen to all of my model class. Please help me.
To solve this, you need to make all your fields public and not protected as they are now, otherwise the annotations will not work.
Now, the annotation takes into account both the field name as well as the getter/setter names to serialize. You have this problem because the fields as well as the getter/setters were getting serialized and that's why are resulting duplicates.
So use the annotation on the field name which are public and ignore the getter/setters. This will solve your problem. Your data will be properly serialized with the property name you want and there will be no duplicates as well.
Try to mark with #PropertyName your getters instead of fields. Another option that may be working - mark with #Exclude your getters.
Related
Currently I have this model class to collect data from firebase database. To show the data I am using firebaserecycleradapter.
News.class
public class News {
private String message, author, thumb_author, type;
private Long timestamp;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getThumb_author() {
return thumb_author;
}
public void setThumb_author(String thumb_author) {
this.thumb_author = thumb_author;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Long getTimestamp() {
return timestamp;
}
public void setTimestamp(Long timestamp) {
this.timestamp = timestamp;
}
}
But the problem is there is another child named images that consist of pushId and an Object. This is how it looks
news {
message:"value"
author:"value"
thumb_author:"value"
type:"value"
timestamp:"value"
images {
pushId01:"value"
pushId02:"value"
pushId03:"value"
pushId04:"value"
pushId05:"value"
}
}
So my question is how can I add the image child to the news.class or is there any possible solution for this? My possible solution for this is to get the image child data inside the onBindViewHolder using databasereference.
Add a property to represent the images node. Since these are simple string key/value pairs, you can represent it with a Map<String,String>. So:
public class News {
private String message, author, thumb_author, type;
private Long timestamp;
public Map<String,String> images; // this is a new field for the images
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
...
I have a field in the Firestore database that is TimeStamp and is in this format: Quarta-feira, 11 de Outubro de 2017 às 10:24:54 GMT-03:00
It is defined as: map.put("timestamp", FieldValue.serverTimestamp());
According to Firestore instructions, you need to add a annotation, directly to the model class.
I have in my class the TimeStamp field in String. I tried using TimeStamp and it does not work
What is the best way to solve this problem?
Code Class Model:
public class Servicos {
private String nome_produto;
private String duracao;
private String valor;
private String valor_old;
private String categoria;
private String categoria_nome;
private String sub_categoria;
private String sub_categoria_nome;
private String descricao;
private String duracao_milis;
private String timestamp;
public Servicos() {
}
public Servicos(String nome_produto, String duracao, String valor, String valor_old,
String categoria, String categoria_nome, String sub_categoria, String sub_categoria_nome,
String descricao, String duracao_milis, String timestamp){
this.nome_produto = nome_produto;
this.duracao = duracao;
this.valor = valor;
this.valor_old = valor_old;
this.categoria = categoria;
this.categoria_nome = categoria_nome;
this.duracao_milis = duracao_milis;
this.sub_categoria = sub_categoria;
this.sub_categoria_nome = sub_categoria_nome;
this.descricao = descricao;
this.timestamp = timestamp;
}
public String getNome_produto() {
return nome_produto;
}
public void setNome_produto(String nome_produto) {
this.nome_produto = nome_produto;
}
public String getDuracao() {
return duracao;
}
public void setDuracao(String duracao) {
this.duracao = duracao;
}
public String getValor() {
return valor;
}
public void setValor(String valor) {
this.valor = valor;
}
public String getValor_old() {
return valor_old;
}
public void setValor_old(String valor_old) {
this.valor_old = valor_old;
}
public String getCategoria() {
return categoria;
}
public void setCategoria(String categoria) {
this.categoria = categoria;
}
public String getCategoria_nome() {
return categoria_nome;
}
public void setCategoria_nome(String categoria_nome) {
this.categoria_nome = categoria_nome;
}
public String getSub_categoria() {
return sub_categoria;
}
public void setSub_categoria(String sub_categoria) {
this.sub_categoria = sub_categoria;
}
public String getSub_categoria_nome() {
return sub_categoria_nome;
}
public void setSub_categoria_nome(String sub_categoria_nome) {
this.sub_categoria_nome = sub_categoria_nome;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public String getDuracao_milis() {
return duracao_milis;
}
public void setDuracao_milis(String duracao_milis) {
this.duracao_milis = duracao_milis;
}
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
}
Ref Firestore Documentation: Link Firestore
// If you're using custom Java objects in Android, add an #ServerTimestamp
// annotation to a Date field for your custom object classes. This indicates
// that the Date field should be treated as a server timestamp by the object mapper.
DocumentReference docRef = db.collection("objects").document("some-id");
// Update the timestamp field with the value from the server
Map<String,Object> updates = new HashMap<>();
updates.put("timestamp", FieldValue.serverTimestamp());
docRef.update(updates).addOnCompleteListener(new OnCompleteListener<Void>() {
// ...
// ...
Here's an example of how to use ServerTimestamp with a custom Java class:
public class Rating {
private String userId;
private #ServerTimestamp Date timestamp;
public Rating() {}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
}
Try this:
public class Klass {
private Date timestamp;
public Klass() {}
#ServerTimestamp
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
}
My ArrayList is like the attached image.
So, I want to distinct the list and need to post the data to server.
So I have created the Serialized model class like
#SerializedName("VehicleList")
public List<VehicleList> vehicleList = new ArrayList<>();
public static class VehicleList {
#SerializedName("VehicleNumber")
public String vehicleNumber;
#SerializedName("Mileage")
public String mileage;
#SerializedName("Coupons")
public List<Coupons> coupons = new ArrayList<>();
}
public static class Coupons {
#SerializedName("Code")
public String code;
}
My ArrayList like this
List<CodeItem> mList = new ArrayList<CodeItem>();
code item look like this
public class CodeItem {
private String code;
private String status;
private String vehicleID;
private String mileage;
private String date;
public boolean selected;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getVehicleID() {
return vehicleID;
}
public void setVehicleID(String vehicleID) {
this.vehicleID = vehicleID;
}
public String getMileage() {
return mileage;
}
public void setMileage(String mileage) {
this.mileage = mileage;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
Now I want to distinct the data for vehicle id and post it to sever. So how do I distinct the data by VehicleID from this mList?
Thanks in advance
I have a string Json :
{
"title": "PowerPoint Presentation",
"author": "Hana",
"subject": null,
"keywords": null,
"created_date": "2016-03-25 15:11:17",
"modified_date": "2016-03-28 17:27:06",
"creator": null,
"producer": "LibreOffice 5.0",
"pdfversion": null,
"file_size": 149225,
"total_page": 24
}
and Object java
public class ContentInfo {
#JsonProperty("title")
private String title;
#JsonProperty("author")
private String author;
#JsonProperty("subject")
private String subject;
#JsonProperty("keywords")
private String keywords;
#JsonProperty("created_date")
private String createdDate;
#JsonProperty("modified_date")
private String modifiedDate;
// (application name that create original file of PDF)
#JsonProperty("creator")
private String creator;
// (application name that create PDF)
#JsonProperty("producer")
private String producer;
#JsonProperty("pdfversion")
private String pdfversion;
#JsonProperty("file_size")
private long fileSize;
#JsonProperty("total_page")
private long totalPage;
public ContentInfo() {
}
public ContentInfo(String title, String author, String subject, String keywords, String createdDate, String modifiedDate, String creator, String producer, String pdfversion, long fileSize, long totalPage, PageViewSetting page_view_setting) {
this.title = title;
this.author = author;
this.subject = subject;
this.keywords = keywords;
this.createdDate = createdDate;
this.modifiedDate = modifiedDate;
this.creator = creator;
this.producer = producer;
this.pdfversion = pdfversion;
this.fileSize = fileSize;
this.totalPage = totalPage;
this.page_view_setting = page_view_setting;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public String getSubject() {
return subject;
}
public String getKeywords() {
return keywords;
}
public String getCreatedDate() {
return createdDate;
}
public String getModifiedDate() {
return modifiedDate;
}
public String getCreator() {
return creator;
}
public String getProducer() {
return producer;
}
public String getPdfversion() {
return pdfversion;
}
public long getFileSize() {
return fileSize;
}
public long getTotalPage() {
return totalPage;
}
public void setTitle(String title) {
this.title = title;
}
public void setAuthor(String author) {
this.author = author;
}
public void setSubject(String subject) {
this.subject = subject;
}
public void setKeywords(String keywords) {
this.keywords = keywords;
}
public void setCreatedDate(String createdDate) {
this.createdDate = createdDate;
}
public void setModifiedDate(String modifiedDate) {
this.modifiedDate = modifiedDate;
}
public void setCreator(String creator) {
this.creator = creator;
}
public void setProducer(String producer) {
this.producer = producer;
}
public void setPdfversion(String pdfversion) {
this.pdfversion = pdfversion;
}
public void setFileSize(long fileSize) {
this.fileSize = fileSize;
}
}
I am using the below code to map them :
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
data = objectMapper.readValue(this.jsonContentInfoData, ContentInfo.class);
However result ResponseBody is wrong in some field:
"content_info": {
"title": "PowerPoint Presentation"
"author": "Hana"
"subject": null
"keywords": null
"created_date": "2016-03-25 15:11:17"
"creator": null
"producer": "LibreOffice 5.0"
"pdfversion": null
"modified_date": "2016-03-28 17:27:06"
"file_size": 0
"total_page": 0
}
Jackson serializes and deserializes based on the access modifier of your field, in conjunction with the available and properly named getter and setter method.
You can override this feature to insure all private fields are ser/deserialized using:
mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
However, it's decent for testing, but isn't the optimal solution.
Instead, you should in practice use private fields and use public getters/setters to control the serialization and deserialization process.
A public Getter Makes a Non-Public Field Serializable and Deserializable
Unintuitively, the getter also makes the private field deserializable as well – because once it has a getter, the field is considered a property.
A public Setter Makes a Non-Public Field Deserializable Only
In your code, showing the getters/setters:
setPdfversion - Is incorrect: Should be setPdfVersion
getTotalPage(long totalPage) - Is incorrect and is intended to be setTotalPage(long totalPage)
Finally, I think it will help to change the types of totalPage and fileSize from the primitive long to the wrapper object Long. Also change the getter/setters for these fields to match the Long types. Since both of these fields are having issues and are using primitives, it seems possible that Jackson (or your version of it) does not handle primitives.
After a lot of research I've been unable to find a resolution.
I have a JSP page backed by a servlet that I'm setting up to run on the Google App Engine. I've created a bean (Client) to facilitate the transfer of my form fields between the JSP and the servlet. This has been working fine in most cases.
As a part of my servlet, I do some validation on the user-entered form values. If there is validation error I use the RequestDispatcher to forward the request back to the JSP page so that an error message can be shown. When this happens, I get the following error:
org.apache.jasper.JasperException: org.apache.jasper.JasperException: Unable to convert string "02-10-2011" to class "java.util.Date" for attribute "appointmentDate": Property Editor not registered with the PropertyEditorManager
Here are the segments of my code that may be of interest:
public class Client {
public Client() {}
private long clientId;
private String name;
private String address;
private String homePhone;
private String cellPhone;
private String workPhone;
private String fax;
private String city;
private String postalCode;
private String emailAddress;
private String directions;
private String style;
private String decoratingThemes;
private String comments;
private String referralSource;
private boolean emailList;
private Date appointmentDate;
public long getClientId() {
return clientId;
}
public void setClientId(long clientId) {
this.clientId = clientId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getHomePhone() {
return homePhone;
}
public void setHomePhone(String homePhone) {
this.homePhone = homePhone;
}
public String getCellPhone() {
return cellPhone;
}
public void setCellPhone(String cellPhone) {
this.cellPhone = cellPhone;
}
public String getWorkPhone() {
return workPhone;
}
public void setWorkPhone(String workPhone) {
this.workPhone = workPhone;
}
public String getFax() {
return fax;
}
public void setFax(String fax) {
this.fax = fax;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public String getDirections() {
return directions;
}
public void setDirections(String directions) {
this.directions = directions;
}
public String getStyle() {
return style;
}
public void setStyle(String style) {
this.style = style;
}
public String getDecoratingThemes() {
return decoratingThemes;
}
public void setDecoratingThemes(String decoratingThemes) {
this.decoratingThemes = decoratingThemes;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public String getReferralSource() {
return referralSource;
}
public void setReferralSource(String referralSource) {
this.referralSource = referralSource;
}
public boolean isEmailList() {
return emailList;
}
public void setEmailList(boolean emailList) {
this.emailList = emailList;
}
public Date getAppointmentDate() {
return appointmentDate;
}
public void setAppointmentDate(Date appointmentDate) {
this.appointmentDate = appointmentDate;
}
}
The bean declaration on the page:
<jsp:useBean id="Client" class="com.HC.RaveDesigns.Entity.Client" scope="session"/>
The method forwarding the request.
private void dispatchError(String error, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
req.setAttribute("error",error);
RequestDispatcher rd = req.getRequestDispatcher("ManageClient.jsp");
rd.forward(req,resp);
}
This is because user sends you String not Date, and this is your job to convert this text into Date.
The fastest fix will be:
change the parameter type in setter type to String
convert string to Date inside this setter.
Example:
public void setAppointmentDate(String appointmentDate) {
DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
this.appointmentDate = df.parse(appointmentDate);
}
Additionally, you should change getter in the same way or use fmt:formatDate like #duffymo has suggested. Also remember to handle date parse exception - Never trust user input
Use JSTL <fmt:formatDate> in your JSPs. You should be using JSTL.
You need to use DateFormat to parse that String into a java.util.Date:
DateFormat formatter = new SimpleDateFormat("MM-dd-yyyy");
formatter.setLenient(false);
Date d = formatter.parse("02-10-2011");