Generics and JSON

I am using the Play platform. I want to use the renderJSON function with 2 objects as an argument. This is not possible, so I am trying to create a class containing two objects. In order not to create a new class every time, I want to use Generics, but it does not work:

Model:

public class JSONContainer<T> extends Model { private T myT; private StatusMessage mySm; public JSONContainer(T myT, StatusMessage mySm) { this.myT = myT; this.mySm = mySm; } } 

and then:

In the controller function:

 JSONContainer<User> myJ = new JSONContainer(logged,sm); renderJSON(myJ); 

where logged is User, sm is StatusMessage. I get an error message:

 type: 'play.exceptions.JavaExecutionException' 

If I do not use Generics, it works fine. Any idea?

The console gives this output, where line 43 is:

 JSONContainer<User> myJ = new JSONContainer(logged,sm); 

Error

+4
source share
2 answers

Instead of using a JSONContainer, just like me, I think the best way is to go with Collection, as shown in this user guide for GSON made by Google (the JSON mapmaker used by Play apparently) at http: // sites .google.com / site / gson / gson-user-guide # TOC-Collections-Examples :

 Collection collection = new ArrayList(); collection.add(logged); collection.add(sm); renderJSON(collection); 

The collection is good for serialization (Java object for JSON), but not suitable for deserialization (see the GSON User Guide for more information).

It is better, IMHO, to use Collection, rather than JSONContainer, since JSONContainer is not useful in this case and does not provide more options.

0
source

Shared objects cannot be displayed by Hibernate.

You must make an abstract abstract class and create concrete implementations (using User and any other possible values โ€‹โ€‹of T). This should solve the problem.

+1
source

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


All Articles