I am attempting to copy the properties from one Apex class instance to another (without hard coding the property names). See the below example:
public class Post{
public String name { get; set; }
public String topic { get; set; }
public String description { get; set; }
public Post(String jsonString){
Post self = this;
Post post = (Post)JSON.deserialize(jsonString, Post.class);
self = post;
//this = post; "Error: Expression cannot be assigned"
System.debug(self); // {"name":"John Smith", "topic":"Test Topic", "description":"Test descriptions."}
System.debug(this); // {"name":null, "topic":null, "description":null}
}
}
Post post = new Post('{"name":"John Smith", "topic":"Test Topic", "description":"Test descriptions."}');
//post is equal to {"name":null, "topic":null, "description":null}
My question is, how can I set the class properties en masse without explicitly referencing the class properties.
If that is not possible, is it possible to call a wrapper class' constructor during JSON deserialization?
For example:
public class Post{
public String apiKey { get; set; }
public String name { get; set; }
public String topic { get; set; }
public String description { get; set; }
public Post(){
this.apiKey = 'abcd1234';
}
}
Post post = (Post)JSON.deserialize('{"name":"John Smith", "topic":"Test Topic", "description":"Test descriptions."}', Post.class);
//post.apiKey == null;
TestClass someClass = (TestClass)(Type.forName('TestClass').newInstance());
to create a new instance of a class with a no argument constructor, so for your second example, you could use this snippet to create a new instance (with some prefilled fields), then set the rest.. but I'm a little blank on how to do that without the usingSchema
... which is why this is a comment and not an answer..