2011-12-13 21 views
0

我在写一个自定义的javascript转换器,并且我收到一个应该包含int的字符串。 这是我在做什么:在做json反序列化时解析int

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"]); 
    } 

但是,它不工作的条件语句。我需要改变什么?我想测试我得到一个int。

谢谢。

+0

`ConvertToType`返回一个`int`,而不是`bool`。 – canon 2011-12-13 19:34:28

+0

如果转换成功,它将返回请求类型的对象。那么,你正在比较一个对象与布尔值。 – Kakashi 2011-12-13 19:35:41

+0

`我正在写一个自定义JavaScript转换器`为什么? – 2011-12-13 19:39:04

回答

3

更改代码中使用此条件:

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

这不是依靠一个异常被抛出,因为捕获异常的计算成本高昂一个更好的解决方案。

2

这是因为ConvertToType返回请求类型的对象。要将其用作if子句的条件,它必须返回bool

你可以做到这一点,而不是:

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

编辑:早些时候,我提出了在转换null值相等的支票,但后来发现它更可能的方法来抛出一个异常比返回null类型不匹配时。

0

如果您不确定该类型不能是int,则改为使用int.TryParse

MyObject TheObject = new MyObject; 

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