1

I would like to use the REST.JSON Librairy to convert an Object to a JSON-String and back, but i'm encountering some problems.

Let's say the classes i would like to convert is "TFooChild1" and "TFooChild2" which both descend from "TFoo". The classes look like this:

TFoo = class
protected
  Name: string;
  Value: Double;
end;

TFooChild1 = class(TFoo)
private
  Limit: Double;
end;

TFooChild2 = class(TFoo)
private
  Limit: Double;
  WorkerID: Integer;
end;

Creating and converting to JSON would look something like this:

var
  Foo: TFoo;
  s: string;
begin
  Foo := TFooChild1.Create;
  Foo.Name:= '...';
  ... //assign all the Fields
  s := TJson.ObjectToJsonString(Foo);
  Foo.Free;

  //conversion to string is correct...

  Foo := TJson.JsonToObject<TFoo>(s, []);
  //Field "Limit" is lost
end

I'm aware that this (TJson.JsonToObject<TFoo>(s, [])) would never return the type TFooChild1, but that's exactly what i need.

When you convert back to an Object, the Fields of the child classes are lost. How do I avoid this? I can't do JsonToObject<TFooChild1> because I don't know if it's gonna be Child1 or Child2. Any hints?

I've googled if there's maybe a ConvertOption that would include Type information, but i haven't found anything

1 Answer 1

1

Add Rest.JsonReflect to your uses class as you will need to use the [JsonReflect(ctObject,ctObject,TFooInterceptor)] attribute attached to where you are referencing the TFoo class. Then you will have to code a TFooInterceptor object to intercept and handle the appropriate conversion. I would code the ObjectReverter and ObjectConverter overrides and start coding from there. Your TFooInterceptor should descend from TJSONInterceptor. Some examples are in the source REST.Json.Interceptors.pas.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.