JSON.NET can't handle deserializing a simple array?

I created a simple class with one field. class Test{int value;}

If I use the "save links" function and set it to "all" (that is, both objects and arrays), then when I just serialize the array of Test objects, it becomes serialized as a JSON object with a special "$ value" with the values โ€‹โ€‹of the array along with the expected property $ id to save the reference to the array. This is very good, but again it all breaks down from deserialization.

After going through the source code, I found that just because the test for " IsReadOnlyOrFixedSize " is true, it sets the flag " createdFromNonDefaultConstructor " to true, which does not even make any sense, because although it is an array of a fixed size, it is created from the constructor by default, unless it considers a fixed-size array constructor a non-standard constructor. The bottom line is that it should be able to process something so basic, and yet it throws this error: " Cannot preserve reference to array or readonly list, or list created from a non-default constructor ".

How can I deserialize a base array while storing all references in JSON.NET without errors?

+6
source share
2 answers

Having received the same problem, I used List<T> instead of T[] to fix it.

+2
source

Most likely, you do not need a call to ToObject(...) and the type. This should work:

 class Test { public int Value; } class Program { static void Main(string[] args) { var array = new Test[2]; var instance = new Test {Value = 123}; array[0] = instance; array[1] = instance; var settings = new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.All }; string serialized = JsonConvert.SerializeObject(array, settings); // Explicitly call ToObject() and cast to the target type var deserialized = (Test[]) ((JArray)JsonConvert.DeserializeObject(serialized, settings)).ToObject(typeof(Test[])); Debug.Assert(deserialized[0].Value == 123); } } 
+1
source

Source: https://habr.com/ru/post/959148/


All Articles