Why can't I convert my Person object into Json?
My Person Model:
@Entity
public class Person extends Model {
@Id
private Long id;
private String value;
}
A controller method:
import com.fasterxml.jackson.databind.JsonNode;
import models.Person;
import play.Logger;
import play.db.ebean.Model;
import play.mvc.Controller;
import play.mvc.Result;
import views.html.index;
import java.util.List;
import static play.data.Form.form;
import static play.libs.Json.toJson;
...
public static Result getJsonPersons() {
List<Person> persons = new Model.Finder(Long.class, Person.class).all();
JsonNode jsonNode = toJson(persons);
Logger.debug("JSON > "+jsonNode.toString());
return ok(jsonNode);
}
Action route:
GET /persons controllers.Application.getJsonPersons()
Resulting JSON returned by the controller method:
[{},{},{},{},{}]
Your problem is related with field access modifiers in the Person class. Both fields are private hence play.libs.Json.toJson
cannot access them. You have to provide appropriate getter methods or make these field public.
@Entity
public class Person extends Model {
@Id
private Long id;
private String value;
public Long getId() {
return id;
}
public String getValue() {
return value;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With