0

I have following structure of class

public class A{

 public class C{
  //some variable
 }

 public class D{
  // some variable
 }

 public class B{
   public string var1;    public string var2;
   public C objC;
   public D objD;
  }

public static A.B parse(string jsonToParse){
 return (A.B) System.JSON.deserialize)(jsonToParse, A.class) 
}

}

When the parse method is called , I am getting error System.TypeException: Invalid conversion from runtime type A to A.B

The JSON that is passed to parse method is according to B's structure. What went wrong with this code?

Any help is appreciated and thanks in advance :-)

0

2 Answers 2

3

You need to put proper structure of the class. So, instead of A.class it will be A.B.class in the parse method.

public static A.B parse(string jsonToParse){
 return (A.B) System.JSON.deserialize(jsonToParse, A.B.class);
}

For more information, refer JSON Class

1

Technically, the outer class name space is not necessary when referring to it from the inner class. Unless you're really trying something tricky, I advise that you only refer to the inner class directly, and that the cast type and the source class type match exactly.

The general syntax for this method should be:

public static T parse(String jsonString) {
  return (T) JSON.deserialize(jsonString, T.class);
}

Where T refers to a specific data type (and, notably, the same data type).

Your example could be modified as:

public class A {
  public class B {
  ...
  }
  ...
  public static B parse(String jsonString) {
    return (B)JSON.deserialize(jsonString, B.class);
  }
}

Also, sometimes you'll see the outer class referred to, and then the inner class is returned:

public static U parse(String jsonString) {
  return ((T)JSON.deserialize(jsonString, T.class)).U;
}

Where T and U are the outer and inner classes, respectively.

You must log in to answer this question.

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