Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 347
John Avatar asked May 16 '16 16:05

John


People also ask

How do I convert an object to a JSON string?

Using TJSON you can convert an object to a JSON string and back with a little help from generics along the way. The following code uses a class called TFoo that has a Foo and a Fee property (string and Integer) Using TJson you can then see how to covert the object to a string and back ready for storage, transport etc.

Is it possible to serialize objects to JSON with Delphi?

Serializing objects to Json as well as de-serializing them with the Delphi standard libraries has been subject to many discussions. While the majority suggests to use another library or a self implemented solution, there are others who would prefer the built-in tools for a couple of reasons.

How flexible is Delphi with JSON data?

Delphi has become very flexible when it comes to handling JSON data. However, as I had to find out myself today: to get to know about this flexibility is a chore. First of all, the documentation never tells us to look in REST.Json for all the neat stuff instead of System.JSON .

Where is ‘formating’ in Delphi JSON?

It is not there. And – for the record – the typo (‘formating’) is not mine either… The naming inconsistency with ‘JSON’ and ‘Json’ is also copied from the Delphi sources. You will find it in REST.Json instead.


1 Answers

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.

like image 172
David Heffernan Avatar answered Oct 09 '22 15:10

David Heffernan