4

I have written the following WrapperClass, consisting different object records/rows/fields as members. How can I dynamically update this wrapper class object. In below code i have used only two fields (id, name), but in future we cannot expect these two fields are coming. Like we can get dynamically phone, email, DOB, State, country... etc fields from different objects to wrapper class. based on different object fields/ records/rows how can i update the wrapper class object Dynamically.

set<string> ids= new set<string>();
        List<fieldWrapper> datalist1 = (List<fieldWrapper>) JSON.deserialize(Datalist,List<fieldWrapper>.class);

        for(fieldWrapper wrapper: datalist1)
        {
            If(Filedvalue =='id'){
            ids.add(wrapper.id);
            }
            If(Filedvalue =='Name')
            {
               ids.add(wrapper.Name);
            }            
        }
        If(Filedvalue =='id'){
              query+=':ids';
            }
            If(Filedvalue =='Name')
            {
              query+=':ids';

         } 


        List<sObject> sobjList = Database.query(query);
        return sobjList;

    public class fieldWrapper
    {
        public string id;
        public string Name;
    }
1

As far as I know, wrapper classes are inherently strongly typed. They're there so that you know what object you're getting and how to access it and its fields.
If you want something dynamic, then maybe this isn't the best solution for you.
Have tried using a Map<String, Object> instead?

Based on the code you shared it looks like you're building a query string from some kind of client side input. If that's the case, then all you care about is what the name of the field is and what value needs to be queried. In that case a Map should suffice.
The downside here is that you need to make sure that your client is sending the correct object type for the field being queried. But that's strongly vs weakly typed for you.

|improve this answer|||||
1

With the limited information I would say that you do not need to deserialize into a wrapper class. For dynamic deserialization and light usage you could simply use deserializeUntyped:

Map<String,Object> datalist1 = 
    (Map<String,Object>) JSON.deserializeUntyped(Datalist);

Then you can iterate through to get the values

//One spot to define keys you are looking for since it appears you are doing the same thing for both items.
Set<String> keysToAdd = new Set<String>{'Id','Name'};

for(String key: datalist1.keySet())
        {
            If(keysToAdd.contains(key)){
                ids.add((String)datalist1.get(key));
            }
        }
|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.