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:

Class IdOnlyListConverter: JsonConverter {Public Override Bull CanConvert (Type Object Type) {Returns (Typ (IEnumerable) .IsAssignableFrom (objectType) & Object Type! = Typef (string)); } Public override zero WriteJson (JasonSraft Writer, Object Value, JasonSyrailizer Serializer) {Jere Array = New Zero (); Foreign objects (Object item in (Inimerable) value) {PropertyInfoIDProp = Item. Gettype () GetProperty ("id"); If (idapap! = Null & amp; idapap.Canred) {array.ad (jotokan.ofobject (idprof.get value (item, empty)); }} Array.WriteTo (author); } Public Override Bull CanRead {get {return false; }} Public Override Object ReadJson (Type JasonReader Reader, Object Type, Object Existing Value, JasonSiRiLiizer Serializer) {New Non Imulated Expression (); }}

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

Popular posts from this blog

java - org.apache.http.ProtocolException: Target host is not specified -

java - Gradle dependencies: compile project by relative path -

ruby on rails - Object doesn't support #inspect when used with .include -