I have a List of an Object.
public class BusStop {
private String description;
private float lat;
private float lng;
//getter and setter
}
Of which I try to put all its content inside a variable of type String.
I have tried this:
StringBuilder aux = new StringBuilder();
busStop.forEach(aux::append);
return aux.toString();
But the response I get is not the desired one.
[email protected]@15820f4bes.yo.app.model.BusStop@2022ad11
And this is just what I want to achieve
[{"lat":43.482243622643026,"lng":-3.7942432892720035,"description":"1"},{"lat":43.47775946266253,"lng":-3.8052296173970035,"description":"2"},{"lat ":43.474520695703184,"lng":-3.822567416469269,"description":"3"}]
The problem is that you are calling the toString() method and you don't have it overridden. If the toString() method is not overridden, the parent method is called (in this case the Object method, father of all) and what it does is show the representation of the class and the object. Here is the documentation about it
You would have to create the override something like this
One option is to use
Streams
andmap()
:You must either override the toString() method of the BusStop class or define a specific one that returns the JSON representation of that instance and call it in that forEach() .
Example:
Another option would be to look at FasterXML Jackson libraries to convert object instances to JSON strings and vice versa.
You can always override the toString() method of the Class, so it could be something like:
Try this method in the class
BusStop
.Departure: