Are you tied to this library? Google Gson is very popular. I have myself not used it with Generics but their front page says Gson considers support for Generics very important.
Answer from Miserable Variable on Stack OverflowAre you tied to this library? Google Gson is very popular. I have myself not used it with Generics but their front page says Gson considers support for Generics very important.
As others have hinted, you should consider dumping org.json's library. It's pretty much obsolete these days, and trying to work around its problems is waste of time.
But to specific question; type variable T just does not have any information to help you, as it is little more than compile-time information. Instead you need to pass actual class (as 'Class cls' argument), and you can then create an instance with 'cls.newInstance()'.
How to serialize to json?
Explain like i'm five - what is Serializable?
Videos
Hi,
I use a library that uses a property name for getter methods (without get prefix - looks like a record but defined as a class)
and by default, Jackson does not serialize such classes. Is it possible to configure Jackson and make it work?
Here is my test:
static class User {
private int age;
User(int age) {
this.age = age;
}
public int age() {
return this.age;
}
}
@Test
public void DD1() throws JsonProcessingException {
ObjectMapper OBJECT_MAPPER = new ObjectMapper();
System.out.println(OBJECT_MAPPER.writeValueAsString(new User(2)));
}
I just don't get it. I'm a junior and see it often in the codebase of the company i work at. Documentation says that it helps serialize and deserialize objects, but why does that need to happen using this interface? There are so many classes that do not implement Serializable, so what happens to them?
Head First Java book says that objects need to be serialized when data is sent over the network or saved to a disk. But there is serialization/deserialization happening to JSON objects for example when they're being sent from server to client and vice versa, and those classes do not implement Serializable.
So in which "special" scenario does one need/want to implement Serializable?