Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json.Net Serialized object losing its Id value

Tags:

json

c#

json.net

I am using Json.Net to serialize and deserialize an object.

I am experiencing an issue where the deserialized object recordPosted has zero as its Id.

Whereas the Serialized record will contain an Id of 180

JsonSerializerSettings jsSettings = new JsonSerializerSettings();
jsSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

var recordAsJson = JsonConvert.SerializeObject(recordToUpdate, 
                                Formatting.None, jsSettings);
//recordAsJson = {"Id":180,....


 var recordPosted = JsonConvert.DeserializeObject<record>(recordAsJson);
 //recordPosted = Id : 0

How would I resolve this?

Edit

public virtual int Id { get; private set; }
like image 502
Nicholas Murray Avatar asked Sep 15 '11 09:09

Nicholas Murray


2 Answers

Json.NET doesn't set private property setters by default. Either make the setter public or place a [JsonProperty] attribute on the property.

like image 76
James Newton-King Avatar answered Oct 26 '22 05:10

James Newton-King


You don't show record, but I would wager that you have something like:

private int id;
public int Id { get { return id; } }

there isn't much that the serializer can do here to set Id, so... it doesn't. Note: some serializers (XmlSerializer, for example) will also refuse to serialize such, but JSON serializers tend to be more forgiving, since it is pretty common to use only the serialize, to return data from a web-server to a javascript client, including from anonymous types (which are immutable in C#).

You could try having a private set:

private int id;
public int Id { get { return id; } private set { id = value; } }

(or alternatively)

public int Id { get; private set; }

If that still doesn't work - it may have to be fully public:

private int id;
public int Id { get { return id; } set { id = value; } }

(or alternatively)

public int Id { get; set; }
like image 1
Marc Gravell Avatar answered Oct 26 '22 06:10

Marc Gravell