c# - Newtonsoft.Json: How can I map specific properties? -


imagine have class one:

public class foo {     [jsonproperty("a")]     public int a;      [jsonproperty("b")]     public int b;      public list<foo> foos; } 

and imagine have json one:

{ "a": "0", "b": "1", "morefoos": {     "total" : "2",     "foos" : [         {             "a" : "2",             "b" : "3"         },          {             "a" : "4",             "b" : "5"         }     ] } } 

so, want deserialize jsonconvert.deserializeobject(foo) properties, right "a" , "b" deserialized. have tried put on foos property:

[jsonproperty("morefoos.foos")] public list<foo> foos; 

but not work, foos null. know if there way map properties dynamically way? of course, avoid creating new class int property called "total" , 1 called foos list of foo objects.

regards, román.

one possibility serialize list in private nested proxy type, so:

public class foo {     struct listwrapper<t>     {         public int total { { return (foos == null ? 0 : foos.count); } }          [jsonproperty(defaultvaluehandling=defaultvaluehandling.ignore)]         public list<t> foos { get; set; }          public listwrapper(list<t> list) : this()         {             this.foos = list;         }     }      [jsonproperty("a")]     public int a;      [jsonproperty("b")]     public int b;      [jsonignore]     public list<foo> foos;      [jsonproperty(defaultvaluehandling = defaultvaluehandling.ignore)]     listwrapper<foo>? morefoos     {                 {             return foos == null ? null : (listwrapper<foo>?)new listwrapper<foo>(foos);         }         set         {             foos = (value == null ? null : value.value.foos);         }     } } 

(i'm using wrapper struct instead of class avoid problem objectcreationhandling set reuse, in proxy wrapper class never set after being gotten , filled in.)

another option use jsonconverter dynamically restructure data, along lines of can serialize nested properties class in 1 operation json.net?, tweaked because class recursive.


Comments

Popular posts from this blog

Email notification in google apps script -

c++ - Difference between pre and post decrement in recursive function argument -

javascript - IE11 incompatibility with jQuery's 'readonly'? -