When writing up the title to this question, I happened upon this answer. However I'm looking for a way to do this in a WCF client. Is there a way to plug JSON.Net into a WCF client?
Yahoo! just changed its PlaceFinder service a couple of days ago. One change is that responses no longer contain a Results
node, instead they now contain a Result
node. Another change is that sometimes this node contains an array of result objects (when there are 2 or more results) and other times it contains a single result object (when there is only 1 result).
Is there a way to use WCF DataMemberAttribute
s to deserialize this kind of structure, accommodating for both scenarios?
[DataContract]
public class PlaceFinderResultSet : IEnumerable<PlaceFinderResult>
{
// this works for 1 result, but fails when it is an array
[DataMember(Name = "Result")]
public PlaceFinderResult Result { get; set; }
// this works for an array of results, but fails when it is a single
[DataMember(Name = "Result")]
public List<PlaceFinderResult> { get; set; }
// note I do not use these together at the same time, but comment one out
// at a time. Other members in this class work as expected and are omitted
}
Here are 2 example responses as seen in Fiddler2 (again, some parts of the result are omitted):
JSON (here is a response with 1 result)
|--ResultSet
|--|--Found=1
|--|--Quality=37
|--|--Result
|--|--|city=city name
|--|--|country=country name
|--|--|otherprops=other values
JSON (here is a response with many results)
|--ResultSet
|--|--Found=2
|--|--Quality=40
|--|--Result
|--|--|{}
|--|--|--|city=city name1
|--|--|--|country=country name1
|--|--|--|otherprops=other values1
|--|--|{}
|--|--|--|city=city name2
|--|--|--|country=country name2
|--|--|--|otherprops=other values2