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?
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.
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.
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 .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With