I would like to know if it is possible to create objects of the same class with different variables each time in Java.
Example:
This method returns data from a URL with a JSON file and I would like to use it to create a post object.
ObjectMapper mapper = new ObjectMapper();
public Post getData(String ... url) throws StreamReadException, DatabindException, MalformedURLException, IOException {
return mapper.readValue(new URL(url[0]), Post.class);
}
But the .JSON may be:
{ "name": "Bob" }
But also:
{ "color": "Red", "width": "200", "height": "150" }
Or anything else.
CodePudding user response:
If Post
is a subclass of Map or JsonNode, then yes, it can hold any key-value pairs.
If Post
looks like this, then no, it's strictly defined as only having one field.
public class Post {
String name;
}