简体   繁体   中英

Json Deserialized Stream Return Type

Hi i have a stream returned from a http response. i have deserialized it as Object(obj) and wanted to check the type of obj to MyObject or string or double. Is the procedure wrong or my concepts are wrong. Please help.

DataContractJsonSerializer obj = new DataContractJsonSerializer(typeof(Object));
        Object Obj = obj.ReadObject(_stream) as Object;
        Product p = new Product();
        List<string> ls = new List<string>();
        List<DisplayProduct> displs = new List<DisplayProduct>();

         if (Obj.Equals(p))
            Console.WriteLine("PRODUCT");
        else if (Obj.Equals(ls))
            Console.WriteLine("LIST OF STRING");
        else
            Console.WriteLine("DISPLAY PRODUCT LIST");

Rain,

You can use the 'is' or 'as' keyword, instead of doing what you're trying to do.

The difference is that as operator is like a cast operation. However, if the conversion is not possible, as returns null instead of raising an exception. Consider the following expression:

expression as type

It is equivalent to the following expression except that expression is evaluated only one time.

expression is type ? (type)expression : (type)null

Example of how you would use as :

       Derived d = new Derived();

       Base b = d as Base;

By contrast, the is expression evaluates to true if the provided expression is non-null, and the provided object can be cast to the provided type without causing an exception to be thrown.

The is keyword causes a compile-time warning if the expression is known to always be true or to always be false, but typically evaluates type compatibility at run time.

Here's how you might use is :

if (obj is MyObject)
{
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM