1

I'm having some trouble deserializing with JSON.Net in a particular scenario.

I make a request to the server and serialize an object with JSON.Net that contains a collection. I then need to add an object to that collection in my web app, but I round trip to the server to get an initialized object to insert into my collection client side. I then insert into my collection and try to save, but I get an error as newly initialized object has the same $id as something else already in the collection.

So my JSON being received by the server is in this general shape:

{ 
  "$id": 1, 
  name: "random",
  myArr: [
    {"$id": 2, blah: "something"},
    {"$id": 1, blah: "This is the item inserted into the collection on the client.
This is the one causing the deserialization error. 
Note that the $id is the same as another $id already in this object graph"},
  ]
  }
}

Do I have to manually manage the $id's myself to avoid this, or is there something baked into JSON.net to get around this?

Ciaran O'Neill
  • 2,572
  • 6
  • 34
  • 40

1 Answers1

1

$id is auto-generated by Json.NET, but you can tell the formatter not to generate a $id. See the following question: how to remove $id during JSON serialization

You can also just remove the $id property on the client-side:

delete item.$id;
Community
  • 1
  • 1
Travis Schettler
  • 844
  • 1
  • 6
  • 10
  • Or, don't add the `"$id"` in the first place. It should only be added by Json.NET, not by by client-side javascript. – dbc Jan 26 '16 at 22:06
  • 1
    Json.NET is adding it, the new object is being retrieved from the server: _"but I round trip to the server to get an initialized object to insert into my collection client side"_ – Travis Schettler Jan 26 '16 at 22:12
  • I need to preserve the reference handling in most of my cases so in this case just deleting item.$id is my best bet – Ciaran O'Neill Jan 28 '16 at 12:42