开发者

Json.Net Serialized object losing its Id value

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; }


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


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; }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜