1

I have a wrapper class and we are deserializing the JSON data, and now we have to send that wrapper class to another method which is in another class.

  1. How we have to send it as a parameter?
  2. How to access it in another class?

This is what our approach till now.

JSONWrapper mapRequest1 = (JSONWrapper) JSON.deserialize(request.requestBody.toString(),JSONWrapper.class); 
  • JSONWrapper --- Name of the Wrapper class

  • request --- Contains Json data

  • mapRequest1 --- Contains Deserialized data

1 Answer 1

3

It will be normal call to second method with JSONWrapper parameter in that method.

See example below

public class JSONWrapper {
    public String firstName;
    public String lastName;
    public static JSONWrapper parse(String json) {
        return (JSONWrapper) System.JSON.deserialize(json, JSONWrapper.class);
    }
}

First Class where JSON will be parsed and passed to second class's method

public class FirstClass {
    public static void firstMethod()
    {
        string jsonRequest='{"firstName":"Dhanik","lastName":"Sahni"}';
        JSONWrapper wrapper=JSONWrapper.parse(jsonRequest);
        SecondClass secObj=new SecondClass();
        secObj.secondMethod(wrapper);
    }
}

Second Class where JSONWrapper object will be passed as parameter

public class SecondClass {
    public void secondMethod(JSONWrapper request)
    {
     system.debug('request : '+ request.firstName);
    }
}
2
  • I tried the same but it throws the below error Invalid datatype : JSONwrapper in second class
    – Naveen
    Commented Oct 12, 2019 at 8:12
  • It is working code. Looks like you have created JSONWrapper in first class. If this is the case then you have to refer it like FirstClass.JSONWrapper in second class method. Commented Oct 12, 2019 at 8:35

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .