Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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:

[{},{},{},{},{}]
like image 511
Adam Barczewski Avatar asked Nov 29 '14 14:11

Adam Barczewski


1 Answers

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;
    }
}
like image 186
Daniel Olszewski Avatar answered Oct 13 '22 22:10

Daniel Olszewski