weixin_33721344 2016-03-31 00: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 00: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.

    展开全部

    评论
    编辑
    预览

    报告相同问题?

    悬赏问题

    • ¥15 PADS Logic 原理图
    • ¥15 PADS Logic 图标
    • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
    • ¥20 气象站点数据求取中~
    • ¥15 如何获取APP内弹出的网址链接
    • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
    手机看
    程序员都在用的中文IT技术交流社区

    程序员都在用的中文IT技术交流社区

    专业的中文 IT 技术社区,与千万技术人共成长

    专业的中文 IT 技术社区,与千万技术人共成长

    关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

    关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

    客服 返回
    顶部