PTLearner PTLearner - 11 months ago 44
C# Question

Newtonsoft don't serialize objects with same values, distinct objects

I'm having difficulties using

when it comes to serialize objects that came from the server side.

I have a collection
with two elements, if some of those elements of that ObjectExample are the same, it only serializes one of them.

Examples below:

(since "Nome da Entidade" or "Tipo de Entidade" are different it shows, if not it only show one, but they are different.)

"Nome da Entidade" and "Tipo de Entidade" are referenced to tables in database.

enter image description here

I'm using linq to return the values and then serialize them like this:

json = JsonConvert.SerializeObject(ins /*LIST*/, Formatting.Indented,
new JsonSerializerSettings
PreserveReferencesHandling = PreserveReferencesHandling.Objects,
DefaultValueHandling = DefaultValueHandling.Include,
ObjectCreationHandling = ObjectCreationHandling.Auto

Answer Source

I don't understand your example, but it looks like this is happening because you're using PreserveReferencesHandling.Objects. If you look at the JSON, you will probably see $ref references in it referencing the objects that have already been serialized.

You could walk the data in your JSON consumer to resolve these references, but you can prevent this behavior by using PreserveReferencesHandling.None. However, this may cause a problem if your .NET objects have circular references. If that is a possibility, you may need to weigh these two options and find the one that's easier for you to solve.