c# - Deserializing Variant JSON Types -
i'm using newtonsoft json converter deserialize json text, have slight problem, array of objects returned me web service, , other times it's single object, let me give example of mean:
{ "t":{ "s":"054", "t":"8", "d":"548" } } one array whereas other single object.
{ "t":[ { "s":"054", "t":"8", "d":"548" }, { "s":"054", "t":"8", "d":"548" }, { "s":"054", "t":"8", "d":"548" } ] } when try deserialize using newtonsoft, error because it's expecting array , receives single object, there way around this?
you can check type of first property :
jobject obj = jobject.parse(json); if (obj["t"] jarray) { // hit on second case } else { // hit on first case } after that's, can deserialize object on list<t> or t.
hope it's !
edit : pastebin classes, have rebuild them , add callback on ondeserialized :
class jsonresponse { public line root; } class line { [jsonproperty("time")] public timestamp time { get; set; } [jsonproperty("s")] public list<station> s { get; set; } } class timestamp { [jsonproperty("@timestamp")] public string @timestamp { get; set; } } class station { [jsonproperty("@code")] public string @code { get; set; } [jsonproperty("@n")] public string @n { get; set; } [jsonproperty("p")] public list<platform> p { get; set; } } class platform { [jsonproperty("@n")] public string @n { get; set; } [jsonproperty("@code")] public string @code { get; set; } [jsonproperty("t")] public jtoken t { get; set; } [ondeserialized] internal void ondeserializedmethod(streamingcontext context) { if (this.t != null) { if (this.t jarray) { this.trains = jsonconvert.deserializeobject<list<train>>(this.t.tostring()); } else { train t = jsonconvert.deserializeobject<train>(this.t.tostring()); this.trains = new list<train>() { t }; } } } public list<train> trains; } class train { [jsonproperty("@s")] public string @s { get; set; } [jsonproperty("@t")] public string @t { get; set; } [jsonproperty("@d")] public string @d { get; set; } [jsonproperty("@c")] public string @c { get; set; } [jsonproperty("@l")] public string @l { get; set; } [jsonproperty("@de")] public string @de { get; set; } } you got trains, on platform.trains property
Comments
Post a Comment