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.

    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效