The PreserveReferencesHandling option will not deserialize references correctly if an object's "$id" property appears after other properties where the object is referenced:
{
"circularRef": { "$ref": "1" }, /* does not resolve */
"$id": "1"
}
Such JSON may be produced by web browser JSON.stringify functions. According to https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/stringify:
"Properties of non-array objects are not guaranteed to be stringified in any particular order. Do not rely on ordering of properties within the same object within the stringification."
In practice, it seems browsers stringify properties in the order that they were added to the object, so a workaround is, if you want to add an "$id" property to an object, first remove all the properties from the object, then add the "$id" property, then add back all the original properties. Of course, this little hack relies on the thing Mozilla just told us not to rely on.
In order to support $id/$ref reference handling from JSON stringified by a web browser, JSON.NET should not rely on the order that the "$id" property appears within an object.
Comments: ** Comment from web user: bman654 **
{
"circularRef": { "$ref": "1" }, /* does not resolve */
"$id": "1"
}
Such JSON may be produced by web browser JSON.stringify functions. According to https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/stringify:
"Properties of non-array objects are not guaranteed to be stringified in any particular order. Do not rely on ordering of properties within the same object within the stringification."
In practice, it seems browsers stringify properties in the order that they were added to the object, so a workaround is, if you want to add an "$id" property to an object, first remove all the properties from the object, then add the "$id" property, then add back all the original properties. Of course, this little hack relies on the thing Mozilla just told us not to rely on.
In order to support $id/$ref reference handling from JSON stringified by a web browser, JSON.NET should not rely on the order that the "$id" property appears within an object.
Comments: ** Comment from web user: bman654 **
I've just discovered that this is also a problem when using the TypeNameHandling facility. It does not work if the $type property is not the first property in the serialized JSON.