WCF中的动态对象不可能?

时间:2013-07-23 09:48:42

标签: c# wcf serialization

在WCF(json)中构建响应时,我很确定不可能使用完全动态的对象,但只是想先在这里仔细检查。

理想的回答看起来像:

"userTypes"  :
                    {
                        "BartSimpson" :
                            {
                                "url" : "foo",
                                "desc" : "bar"
                            },
                        "LisaSimpson" :
                            {
                                "url" : "foo",
                                "desc" : "bar"
                            }
                    }

在“编译”代码中,上述内容可以通过以下架构(稍微伪代码)执行:

public class Character{
string url {get;set;}
string desc{get;set;}
}

public class UserTypes{
 public Character BartSimpson{get;set;}
 public Character LisaSimpson{get;set;}
}

但我的主要目标是BartSimpsonLisaSimpson不会被“编译”,所以我可以拥有任意数量的Character类,任何名称/在回应中确定。

1 个答案:

答案 0 :(得分:5)

在服务实现类的顶部添加以下using(确保您还在项目中添加了正确的引用):

using Newtonsoft.Json;
using System.Dynamic;
using System.IO;
using System.Text;

您可以尝试这种输出动态结果的简单方法:

public string GetData()
{
    dynamic d = new ExpandoObject();
    dynamic bartSimpson = new ExpandoObject();
    dynamic lisaSimpson = new ExpandoObject();
    bartSimpson.url = "foo";
    bartSimpson.desc = "bar";
    lisaSimpson.url = "foo";
    lisaSimpson.desc = "bar";
    d.userTypes = new ExpandoObject();
    d.userTypes.BartSimpson = bartSimpson;
    d.userTypes.LisaSimpson = lisaSimpson;
    var s = JsonSerializer.Create();
    var sb = new StringBuilder();
    using (var sw = new StringWriter(sb))
    {
        s.Serialize(sw, d);
    }
    return sb.ToString();
}

再往前走一步(你只需要在comaSeparatedNames值中传递Bart和Lisa),你可以这样做:

public string GetData(string comaSeparatedNames)
{
    string[] names = comaSeparatedNames.Split(',');
    dynamic d = new ExpandoObject();
    dynamic dNames = new ExpandoObject();
    foreach (var name in names)
    {
        dynamic properties = new ExpandoObject();
        properties.url = "foo";
        properties.desc = "bar";
        ((IDictionary<string, object>)dNames).Add(name, properties);
    }
    ((IDictionary<string, object>)d).Add("userTypes", dNames);

    var s = JsonSerializer.Create();
    var sb = new StringBuilder();
    using (var sw = new StringWriter(sb))
    {
        s.Serialize(sw, d);
    }

    // deserializing sample
    //dynamic dummy = new ExpandoObject();
    //var instance = s.Deserialize(new StringReader(sb.ToString()), 
    //    dummy.GetType());
    //var foo = instance.userTypes.BartSimpson.url;

    return sb.ToString();
}

注意:我还提供了用于反序列化的行(注释)。