I have two classes:
public class Team {
private Long id;
private String name;
...
}
public class Event {
private Long id;
#ManyToOne
private Team homeTeam;
#ManyToOne
private Team guestTeam;
...
}
Controller:
public #ResponseBody List<Event> getAll() {...
}
Now I have Json:
[{"id":1,"homeTeam":{"id":2,"name":"Golden State"},"guestTeam":{"id":1,"name":"Philadelphia"},...
What I want:
[{"id":1,"homeTeam":"Golden State","guestTeam":"Philadelphia",...
How I can point Jackson to output only name of Team instead of full Object?
Benoit's answer will not generate JSON of the desired form, it would produce something like this:
[{"id":1,"homeTeam":{"name":"Golden State"},"guestTeam":{"name":"Philadelphia"},...
Instead what you want to do is make your Team class look something like this:
public class Team {
private Long id;
private String name;
public Long getId() {
return id;
}
#JsonValue
public String getName() {
return name;
}
...
}
This will produce the desired JSON:
[{"id":1,"homeTeam":"Golden State","guestTeam":"Philadelphia",...
But may require additional handling for deserialization.
Exclude all properties of the Team object except the name using : #JsonIgnoreProperties
#JsonIgnoreProperties
public String getPropertyToExclude() {
return propertyToExclude;
}
So that Jackson will serialize only the Team name in the JSON.
Related
Java Class
public class Employee{
#JsonProperty("NAME")
private String name;
#JsonProperty("NAME")
public String getName() {
return name;
}
#JsonProperty("NAME")
public void setName(String name) {
this.name = name;
}
}
Input Json String {"NAME":"xxxx"}
ObjectMapper mapper=new ObjectMapper();
Employee employee = mapper.readValue(jsonMessage, Employee.class);
system.out.println(employee.toString);
output === {"name":"xxxx"}
while mappring json string to java class, Is there any way to tell to use #JsonProperty instead of getterMethod ?
if I print object, expecting same output as input.
You confused System.out.println which does not obey any Jackson annotation with a classical String employeeAsString = mapper.writeValueAsString(employee).
Try the latter one and you'll get your field name in uppercase.
I have a class with lots of attributes which are required for server side logic, but a few of those are required for UI. Now when I am creating a json from the class, all the attributes are written to json. I want to ignore some values only when it is converted to json. I Tried with #JsonIgnore. But it is not working.
My Class Is
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
#JsonIgnoreProperties(ignoreUnknown = true)
public class Student {
#JsonProperty("id")
protected Integer id;
#JsonProperty("name")
protected String name;
/**
* This field I want to ignore in json.
* Thus used #JsonIgnore in its getter
*/
#JsonProperty("securityCode")
protected String securityCode;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#JsonIgnore
public String getSecurityCode() {
return securityCode;
}
public void setSecurityCode(String securityCode) {
this.securityCode = securityCode;
}
}
And I am writing this using
public static StringBuilder convertToJson(Object value){
StringBuilder stringValue = new StringBuilder();
ObjectMapper mapper = new ObjectMapper();
try {
stringValue.append(mapper.writeValueAsString(value));
} catch (JsonProcessingException e) {
logger.error("Error while converting to json>>",e);
}
return stringValue;
}
My Expected json should contain only :
id:1
name:abc
but what I am getting is
id:1
name:abc
securityCode:_gshb_90880..some_value.
What is wrong here, please help
Your #JsonProperty annotation overrides #JsonIgnore annotation. Remove #JsonProperty from securityCode and your desired json output will be produced.
If you want more advanced ignoring / filtering please take a look at:
#JsonView : http://wiki.fasterxml.com/JacksonJsonViews
#JsonFilter : http://wiki.fasterxml.com/JacksonFeatureJsonFilter
I am trying to make a simple round-trip with a REST API that leads to storing an entity into the db and then returns the stored entity.
Going down works fine and the entity is stored and correctly returned to the REST Controller. However, when I return it, Jackson seems to serialize it incorrectly, as the "name" attribute is not included.
This is the entity:
#Entity
#Configurable
public class MyEntity extends IdentifiableEntity {
private String name;
protected MyEntity() {
};
public MyEntity(String name) {
this.name = name;
}
}
and the extended entity:
#Configurable
#Inheritance(strategy = InheritanceType.JOINED)
#Entity
public abstract class IdentifiableEntity {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private Long id;
#Version
#Column(name = "version")
private Integer version = 1;
public String toString() {
return ReflectionToStringBuilder.toString(this,
ToStringStyle.SHORT_PREFIX_STYLE);
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getVersion() {
return this.version;
}
public void setVersion(Integer version) {
this.version = version;
}
}
The REST controller is:
#RestController
#RequestMapping("/service")
public class Service {
#RequestMapping(value = "/public/{name}", method = RequestMethod.GET)
public MyEntity storeEntityPublic(#PathVariable String name) {
System.out.println("Hello " + name
+ ", I am saving on the db. (PUBLIC)");
MyEntity saved = controller.saveEntity(name);
return saved;
}
}
Then my business logic:
#Service
public class LogicController {
#Autowired
private MyEntityRepository myEntityRepository;
public MyEntity saveEntity(String name) {
MyEntity cg = new MyEntity(name);
return myEntityRepository.save(cg);
}
}
I am using Spring repositories:
#Repository
public interface MyEntityRepository extends JpaSpecificationExecutor<MyEntity>,
JpaRepository<MyEntity, Long> {
}
The returned JSON is:
{"id":12,"version":1}
Where is my "name" attribute? Is is set in the variable being returned by the REST controller.
I found the trick: MyEntity needs to have a public get for the property that has to be shown. A good reason to use a DTO pattern.
In response to your "I don't want to have my Entity "dirty"" comment: Jackson allows the use of so-called Mixins. They allow you to define annotations for your class outside the class itself. In your case it could look like this:
public abstract class MyEntityMixin {
#JsonProperty
private String name;
}
You may keep it as a field and annotate the field with #JsonProperty if you like.
The thing is that I want to hide the null elements from a RESTFul JSON response (if it's possible).
The REST controller retrieves the information from a Mongo database and because this elements doesn't exist there I would like to ignore them when they are null.
This is my REST Controller (exposed with Jersey):
#Stateless
#TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
#Path(PropertiesRestURIConstants.PROPERTIES)
#Produces(MediaType.APPLICATION_JSON)
#RequestScoped
public class GetPropertiesController {
#EJB(mappedName = PropertiesManagerRemote.MAPPED_NAME)
PropertiesManagerRemote propertiesManager;
#GET
#Path(PropertiesRestURIConstants.PROPERTIES_ALL)
public List<PropertyEntity> getAllProperties() throws DBLayerException {
return propertiesManager.getAllProperties();
}
...
...
...
}
This is my entity:
#Document(collection = "property")
public class PropertyEntity implements GenericEntity {
#Id
private String id;
private String propertyName;
private String propertyValue;
public PropertyEntity() {
}
public PropertyEntity(String propertyName, String propertyValue) {
this.propertyName = propertyName;
this.propertyValue = propertyValue;
}
...
...
...
}
And this is the result:
[{"id":"542c00c2ff5e0ba4ea58790d","propertyName":"property1","propertyValue":null},{"id":"542c00c2ff5e0ba4ea58790e","propertyName":"property2","propertyValue":null},{"id":"542c00c2ff5e0ba4ea58790f","propertyName":"property3","propertyValue":null}]
I use Spring Data for the persistence layer. I tried with JSONIgnore annotations and similar things, but nothing works for me.
Any help will be welcome.
Thanks in advance.
Try to annotate it this way:
#JsonInclude(Include.NON_EMPTY)
public class PropertyEntity implements GenericEntity {
Im very new to Hibernate so this will probably a easy task for you guys.
As the Topic says I'm trying to reference the same entity in multiple Lists. But when I try to do so I get an exception saying: "Duplicate entry '5' for key 'military_id'".
I googled but could not find a solution to my problem.
I have an Entity called MilitaryUnitData like this:
#Entity
public class MilitaryUnitData implements IMovable{
private long Id;
//snip
#Id
#GeneratedValue(strategy=GenerationType.TABLE)
public long getId() {
return Id;
}
public void setId(long id) {
Id = id;
}
//snip
}
and a class City where I want to store my units in.
#Entity
public class CityData {
private Collection<MilitaryUnitData> military = new ArrayList<MilitaryUnitData>();
private String name;
//snip
#Id
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#OneToMany
#Column(nullable=false)
public Collection<MilitaryUnitData> getMilitary() {
return military;
}
public void setMilitary(Collection<MilitaryUnitData> military) {
this.military = military;
}
//snip
}
The problem occurs when I want to put a Unit into 2 cities at the same time.
How do I have to change the mapping to achive this?
Thx in advance.
I'm trying to reference the same entity in multiple Lists
After looking at your code, I think you mean, that the same MilitaryUnitData is used in several CityData?
IF this is correct, than the realtion ship is a M:N relation ship, and you need to use a #ManyToMany instead of an #OneToMany.