Why does play.libs.Json.toJson return an empty object?

Why can't I convert a Person object to Json?

My persona Model:

@Entity public class Person extends Model { @Id private Long id; private String value; } 

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); } 

Act:

 GET /persons controllers.Application.getJsonPersons() 

The JSON result returned by the controller method:

 [{},{},{},{},{}] 
+5
source share
1 answer

Your problem is with field access modifiers in the Person class. Both fields are private, so play.libs.Json.toJson cannot access them. You must provide the appropriate getter methods or make this 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; } } 
+7
source

Source: https://habr.com/ru/post/1207932/


All Articles