简体   繁体   中英

Play Framework renderJSON gives InvocationTargetException

I am trying to render a user object in JSON format using Play's renderJSON function. However, when I call it I get an InvocationTargetException: null error.

While debugging, i've found that the value I gave for the user's date of birth in the initial-data.yml file is the cause. It is as follows:

User(bob):
  firstName: Bob
  lastName: Bobson
  dob: 1979-01-01

If however I create a User programatically and set their dob with the new Date() constructor, the object rendered without issue. I even tried dob: !!java.util.Date "1979-01-01" as stated in SnakeYML's documentation ( http://code.google.com/p/snakeyaml/wiki/Documentation#YAML_syntax ) to no avail.

What am I doing wrong here?

Eureka! I've got it! After about 9 hours of reading endless SO questions I finally got it through my thick skull that the error came about not because of the Date format, but because the default Gson renderer does not work well (by default) with bi-directional releationships such as @OneToMany and @ManyToOne.

My solution? "Mute" one side of the relationship when the time came for rendering the object as JSON. Using the information found here: User Defined Exclusion Strategies i've come up with the following solution.

/***************** Models ****************/

class Person {
 @Expose
 public int age;
 @Expose
 public String name;
 @Expose
 @OneToMany(mappedBy="owner")
 public Dog dog;

 //Constructors and other code
}

class Dog {
 @Expose
 public String name;
 @ManyToOne(fetch=FetchType.Eager)
 public Person owner;

 //Constructor and other code
}


/**************Controller********************/

public class Application extends Controller {

 public static Gson gson = GsonBuilder.excludeFieldsWithoutExposeAnnotation().create;

 public static void allPersons() {
  List<Person> people = Person.findAll();
  renderJSON(gson.toJson(people));

 //Error should be taken care of
 }
}

Using the @Expose annotation to mute one side of the bi-directional relationship at render time definitely solved the issue. Now I just have to figure out how to work around this new semi-one-sided structure.

Another library I used before discovering this tip was FlexJSON . I might go back to it depending on how things go later down in the application because it works well with bi-directional relationships without requiring you to "mute" one side. It's also (to me) more elegant than the Gson library.

So thank you very much for all the assistance @emt14. I hope this post helps others out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM