I am trying to deserialise a xml output from a REST API. After deserialising, I need to check whether the response has valid data.
public class Response
{
public UserWrapper Users { get; set; }
public MovieWrapper Movies { get; set; }
}
public class UserWrapper
{
[XmlElement("User")]
public User[] UserList { get; set; }
}
public class MovieWrapper
{
[XmlElement("Movie")]
public Movie[] MovieList { get; set; }
}
public static bool isValidUserResponse(this Response response)
{
return response.Users != null && response.Users.UserList != null
}
public static bool isValidMovieResponse(this Response response)
{
return response.Movies!= null && response.Movies.MovieList != null
}
XML Response Structure
<Response>
<Users>
<User>...</User>
<User>...</User>
<User>...</User>
</Users>
</Response>
<Response>
<Movies>
<Movie>...</Movie>
<Movie>...</Movie>
<Movie>...</Movie>
</Movies>
</Response>
How do I make my isValidUserResponse() and isValidMovieResponse() as single generic method?
You can't just use generics for this - at least, not easily. You could write something like:
public static void IsValidResponse<T>(this Response response,
Func<Response, T> firstPropertyFetcher,
Func<T, object> secondPropertyFetcher) where T : class
{
T property = firstPropertyFetcher(response);
return property != null && secondPropertyFetcher(property) != null;
}
and call it with:
response.IsValidResponse(r => r.Users, u => u.UserList);
response.IsValidResponse(r => r.Movies, u => u.MovieList);
... but I'm not sure that's any cleaner.
Or you could use reflection to examine all of the properties within Response
and find ones with the "target" type, and validate those... but it's a bit ugly.
Do you need to validate each part of the response separately? If not, you could consider giving each class its own IsValid
method.
Alternatively, I believe there are some general open source validation projects which may help you - but I don't have any experience with them.
See more on this question at Stackoverflow