c# - Modify the behaviour of JSON.NET to serialize a collection of objects to an array of IDs -
I want to modify JSON.NET so that when I want to serial a model from my API, An array sends an overall collection object.
For example:
class employee {public iconging
Then when I send it via webapp
request. Creatorespress (HTTTPTAS code.OK, new employee ()); Instead of: {"address": [{"id": 1, "location": "XX", "postcode": " XX "}, {" id ": 2," location ":" XX "," postcode ":" XX "}]}
This sends just like this:
{"addresses": [1,2]}
I think this application should be wide and I do not want to modify it in a specific location.
How do I use JSON.NET serializer?
You can do that as a result you want to use a custom like this:
In your model, wherever you have a collection where you only want the ID, specifying the collection code for the [JsonConverter]
attribute For decorating custom converter, for example:
class employee {public string name {get; Set; } [Jason Synergracht (typef (ID Only List Convert))] Public Iconation & lt; Address & gt; {Receive addresses; Set; }} Category Address {Public Ent ID {get; Set; } Public string location {get; Set; } Public string postcode {get; Set; }}
When the archive is serialized, the converter will be used, and only id values will be written. Demo:
class program {static zero main (string [] args) {employee employee = new employee {name = "jo", address = new list & lt; Address & gt; {New address {id = 1, location = "foo", postcode = "bar"}, new address {id = 2, location = "baz", postcode = "quux"}}}; String json = JsonConvert.SerializeObject (emp); Console.WriteLine (json); }}
Output:
{"name": "which", "address": [1,2]}
Comments
Post a Comment