frenchie
frenchie

Reputation: 51927

parsing int when doing json deserialization

I'm writing a custom javascript converter and I'm receiving a string that should contain an int. This is what I'm doing:

public class MyObjectToJson : JavaScriptConverter
{
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{

  MyObject TheObject = new MyObject; 

  if (serializer.ConvertToType<int>(dictionary["TheInt"]) == true)
  {
    MyObject.TheInt = serializer.ConvertToType<int>(dictionary["TheInt"]);
  }

However, it's not working on the conditional statement. What do I need to change? I want to test that I'm getting an int.

Thanks.

Upvotes: 0

Views: 226

Answers (3)

Kakashi
Kakashi

Reputation: 2195

if you have not sure that the type cannot be an int, use int.TryParse instead.

MyObject TheObject = new MyObject; 

  if (!int.TryParse(dictionary["TheInt"], out MyObject.TheInt))
  {
    // conversion to int failed
  }

Upvotes: 0

jmacinnes
jmacinnes

Reputation: 1609

Change your code to use this condition:

 int value;
 if (int.TryParse(serializer.ConvertToType<string>(dictionary["TheInt"]), out value)
 {
    MyObject.TheInt = value;
 }

This is a better solution than relying on an exception to be thrown, as catching exceptions is computationally expensive.

Upvotes: 3

Doug
Doug

Reputation: 6442

It's because ConvertToType returns an object of the requested type. To use it as a condition to an if clause it must return bool.

You can do it instead:

try {
    MyObject.TheInt = serializer.ConvertToType<int>(dictionary["TheInt"]);
}
catch(Exception e)
{
    throw new Exception("Could not convert value into int: " + dictionary["TheInt"]);
}

EDIT: Earlier I proposed a check for null equality on the converted value, but realized that it's more likely for the method to throw an exception than returning null when the types mismatch.

Upvotes: 2

Related Questions