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.

    评论

报告相同问题?

悬赏问题

  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch