Search code examples
jsondelphidelphi-xe7

Converting Delphi Objects to JSON


I am using Delphi XE7 and I am having trouble converting objects into JSON. I can get some object to give back what I think is proper JSON, eg TTestObject:

{"Test":{"Field":"TestField","Operation":"TestOperation","values":
["Value1","Value2","Value3","Value4"]}}
JOBJ:= TJSONObject.Create;
JOBJ.AddPair('Test', ATestObject.JSONObj);
memo1.Lines.Add(JObj.ToJSON);
JOBJ.Free;

However, when I try to get JSON back from my objects that have properties that are objects as well, I get JSON with \ characters.

{"Exceptions":{"TestObject1":"
{\"Mode\":\"0\",\"Value\":\"100.50\",\"Days\":\"10\"}","TestObject2":"
{\"Mode\":\"0\",\"Days\":\"0\",\"UnitsSold\":\" 
...

What is causing this?


Solution

  • The JSON is perfectly valid. Your nested objects, when represented as JSON, contain double quote characters. Since they are reserved as string delimiters they need to be escaped. Hence the use of the backslash character as the escape character.