0

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 ()
    {
    }
}
2
  • What is your RegisterResponse class implementation ? Can you add to your question ? Commented Jul 10, 2012 at 15:34
  • Done. Any more additions are on demand. Commented Jul 11, 2012 at 6:56

1 Answer 1

1

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 Error class and convert that via

JsonConvert.DeserializeObject<Error> (jsonResponse);

And 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.

 JObject o = JObject.Parse(jsonResponse);
 string error = (string)o["Error"];
 if(string.IsNullOrEmpty(error) == false)
    // bad things going down
 // if you get here it's all good
Sign up to request clarification or add additional context in comments.

1 Comment

Yes. My first try was like your solution 1. It is work, but a bit weak cause of manual checking that some fields in Error type is not empty too. Strange that there are no attributes to mark them required to fill for json.net.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.