weixin_33721344 2016-03-31 08:00 采纳率: 0%
浏览 13

序列化动态对象

i'm trying to send data to wcf method, via ajax from client side

public class DynamicParse
{      

    // other properties

    public dynamic Value {get;set;}
}

// wcf method
public void PostData(List<DynamicParse> list)
{
    // parse list[0].Value
}

the javascript array that is sent to the wcf method:

var data = [{ Value : 1 }, { Value : "test" }, { Value : { message : "hello" } }];

my difficulty is how can i parse the data when the "Value" property is an object type-> { message : "hello" } from c#,

i tried reflection and json serialization and no success so far..

is there another option to parse the specified data without dynamic type? or is it suitable here for this problem?

thanks

  • 写回答

1条回答 默认 最新

  • 游.程 2016-03-31 08:18
    关注

    First and foremost, there are no specific data type in JSON. You have to match it with a model.

    Since you seem to want everything dynamic, you can just check the data type of the dynamic property named Value.

    public class DynamicParse
    {      
    
        // other properties
    
        public dynamic Value {get;set;}
    }
    
    // wcf method
    public void PostData(List<DynamicParse> list)
    {
        // parse list[0].Value
        foreach(var entry in list)
        {
            if(entry.Value is int)
            {
                int num = entry.Value;
            }
            else if(entry.Value is string)
            {
                string someString = entry.Value;
            }
            else if(entry.Value is MyCustomClass)
            {
                MyCustomClass myClass = entry.Value;
                // Do something
            }
            else
            {
                // Do something
            }
        }    
    }
    

    The data type of the property Value will be determined by the .NET framework so you just have to check what it is.

    EDIT:

    You can also change the property of DynamicParse Value from dynamic to object, the drawback is you will have to manually cast it.

    public class DynamicParse
    {      
    
        // other properties
    
        public object Value {get;set;}
    }
    

    So you will have to check the value like this..

    if(entry.Value is MyCustomClass)
    {
        MyCustomClass someObject = (MyCustomClass)entry.Value;
    }
    

    For dynamic, no need to cast just assign the value but for object you have to cast it.

    评论

报告相同问题?