I am using JSON web-service. On any JSON request web-service could respond via Error type JSON or Response type. For example:
{
"response": "register",
"error": {
"@c" : "error",
"code": "USER_EXISTS",
"message": ""
}
}
or
{
"response": "register",
"register": {
"session": {
"@c" : "session",
"userId": "18",
"sessionId": "ASFT23WETT234QQW"
}
}
}
Any response I trying to deserialize to type, which is related to request. For example, RegisterResponse when request is RegisterRequest.
If response is Error type response, code
JsonConvert.DeserializeObject<RegisterResponse> (jsonResponse);
created RegisterResponse with all empty poperties values.
How to suggest JSON.NET to throw exception if there is some incompatibility with JSON string and target type?
Classes definitions:
public class Response
{
public string response { get; set; }
public Response ()
{ }
}
public class Session
{
public long userId;
public string sessionId;
public Session ()
{ }
}
public class RegisterResponse: Response
{
public Session session { get; set; }
public RegisterResponse ()
{
session = new Session();
}
}
public class Error
{
public string code;
public string message;
public Error ()
{
}
}
This is not directly JSON.NET’s bag because the conversion you gave it is actually completely valid semantically, you just gave it bad data. The best thing to do would simply be to check your data first. Either create an
Errorclass and convert that viaAnd then test
Error‘s properties to make sure that they are empty the way you’d hope.Alternately you could just decode the single Error property you’re looking for to see if it comes back null.