With the following playload:
var playloads = new Dictionary<string, string>() {
{"FailMessage",
@"{
""success"": ""FALSE"",
""WsResult"": {
""result"": [],
""msg"": ""La r\u00e9f\u00e9rence ...""
}
}"},
{"SuccessMessage",
@"{
""success"": true,
""WsResult"": {
""result"": {
""FooNumber"": {
""Foo1"": {
""Bar1"":""... il y a un probl\u00c3\u00a8me ."",
""Bar2"":""bogus"",
""Bar3"":""bogus""
},
""Foo2"": {
""Bar1"":""bogus"",
""Bar2"":""bogus""
},
}
},
""mssg"": """"
}
}"}
};
In this exemple Result switch from a Dictionary<string, Result>
to an empty array when the Api has no result to serve.
My original mapping class for sucessfull request was:
public class Foo1
{
public string Bar1 { get; set; }
public string Bar2 { get; set; }
public string Bar3 { get; set; }
}
public class Foo2
{
public string Bar1 { get; set; }
public string Bar2 { get; set; }
}
public class Result
{
public Foo1 Foo1 { get; set; }
public Foo2 Foo2 { get; set; }
}
public class WsResult {
public Dictionary<string, Result> result { get; set; }
public string msg { get; set; }
}
public class RootObject
{
public string success { get; set; }
public WsResult WsResult { get; set; }
}
While deserialising Good message works , bad message gave an error :
var resultA = JsonConvert.DeserializeObject<RootObject>(playloads["SuccessMessage"]);
var resultB = JsonConvert.DeserializeObject<RootObject>(playloads["FailMessage"]);
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type
Dictionary<string, Result>
So I try to add an property with this type but failed to make it work with the same property name:
//[JsonProperty("result")]
public List<object> Failresult { get; set; }
I am looking for a simple way to handle those case. The bigger picture is simple: Every response from the API has the same structure with a tricky property result in the middle that has a huge tentency to never return null or negative value (like a false etc) and will always return empty array.
Methode getSomething : Result is either a 'something' or an empty array.
Methode PostSomething : Result is either 1 or empty array.
Methode PostSomething2 : Result is either true or empty array.
Methode GetID : Result is either the int ID or empty array. if not found.
etc..
In Json.net is there a way to choose between property using their type?
Clarification:
It's not about the C# representation of a Json. It's more about mapping same property to different type. But it's not a duplicate of that. An Empty array of Nothing does not carry any informations. So there is no need to map it to anything. But you can just JsonIgnore it as it could be Something else than empty array and carry all the informations.