Reputation: 5053
I have pojo which has many fields. I have set value some field. But when i create json, whole pojo create a json . here is the code i have used:
Pojo
public class BasicInfoModel {
private String client_id="";
private String father_name="";
private String mother_name="";
private String gendar="";
//Getter and setter
}
Repository code
public BasicInfoModel getBasicInfo() {
BasicInfoModel lm = new BasicInfoModel();
lm.setFather_name("Enamul Haque");
return lm;
}
Controller code
@RequestMapping(value = "/get_donar_basic_info", method = RequestMethod.POST, produces ="application/json")
public @ResponseBody BasicInfoModel getBasicinfo(){
return repository.getBasicInfo();
}
But my json is resposne like bellow:
{
"client_id": "",
"father_name": "Enamul Haque",
"mother_name": "",
"gendar": ""
}
I have set value to father_name but i have seen that i have found all the value of pojo fields. I want get only set value of father_name and ignor other value which is not set in repository.
My json look like bellow: I will display only father_name.how to display bellow like json from above code?
{
"father_name": "Enamul Haque"
}
Please help me..
Upvotes: 0
Views: 3144
Reputation: 493
You can ignore field at class level by using @JsonIgnoreProperties annotation and specifying the fields by name:
@JsonIgnoreProperties(value = { "client_id" })
public class BasicInfoModel {
private String client_id="";
private String father_name="";
private String mother_name="";
private String gendar="";
//Getter and setter
}
Or you can use @JsonIgnore annotation directly on the field.
public class BasicInfoModel {
@JsonIgnore
private String client_id="";
private String father_name="";
private String mother_name="";
private String gendar="";
//Getter and setter
}
You can read here more about this.
Upvotes: 0
Reputation: 39978
Json include non null values to ignore null fields when serializing a java class
@JsonInclude(Include.NON_NULL)
@JsonInclude(Include.NON_NULL)
public class BasicInfoModel { ... }
public class BasicInfoModel {
private String client_id="";
@JsonInclude(Include.NON_NULL)
private String father_name="";
private String mother_name="";
private String gendar="";
//Getter and setter
}
from jackson 2.0 use here use
@JsonInclude(JsonInclude.Include.NON_NULL)
You can also ignore the empty values
@JsonInclude(JsonInclude.Include.NON_EMPTY)
Upvotes: 2
Reputation: 107
Add the @JsonIgnoreProperties("fieldname") annotation to your POJO.
Or you can use @JsonIgnore before the name of the field you want to ignore while deserializing JSON. Example:
@JsonIgnore
@JsonProperty(value = "client_id")
@RequestMapping(value = "/get_donar_basic_info", method = RequestMethod.POST, produces ="application/json")
public @ResponseBody BasicInfoModel getBasicinfo(){
return repository.getBasicInfo();
}
Upvotes: 0