Mathew Joy
Mathew Joy

Reputation: 121

Object to Json and back

I am trying to convert an object to Json string. I see an TJson::ObjectToJsonString() which seems to meet the needs but it doesn't seem to work. I have the exact code in Delphi, works with no problem. So evidently something more need to be done on the C++ side.

class TData : public TObject
{
private:
  String FName;
public:
__property String Name = {read=FName, write=FName};
};
//----------------------------------------------------------------

Implementation...

  TData *data = new TData();

  data->Name = "A Test Name";

  mmMessage->Lines->Add(TJson::ObjectToJsonString(data));

I get the output {}

Upvotes: 0

Views: 448

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 596527

ObjectToJsonObject() ignores properties, it only marshals fields, and it is smart enough to strip a leading F from field names. That is why your FName field is marshaled as Name in your Delphi code. See Convert an object instance into a JSON string and making use of custom attributes, which covers this topic in more details (it is geared towards Delphi, but it applies to C++Builder as well).

Since your Name property is fairly useless as-is, you may as well make Name be a public field instead of a property:

class TData : public TObject
{
public:
  String Name;
};

Also make sure your project is setup to generate RTTI for your TData class. Try marking it with __declspec(delphirtti), for instance:

class __declspec(delphirtti) TData : public TObject
{
public:
  String Name;
};

And make sure you are not explicitly disabling RTTI via #pragma explicit_rtti.

Upvotes: 1

Related Questions