帮助我的WCF JSON服务设计DataContract

时间:2011-08-09 02:57:04

标签: wcf json serialization

我正在编写一个WCF服务,它以JSON格式向客户端返回数据。 我想输出JSON,如下所示

{   22877:{     id:“22877”,     名称:“Foo Bar”,     输入:“user”,     活动:{       数据:[       ]     }   }   405564:{     id:“405564”,     名称:“Bar Foo”,     输入:“user”,     活动:{       数据:[       ]     }   } }

我很难想出一个类/ DataContract,它将被WCF JSON服务序列化为上述格式。

我尝试了以下

[DataContract]
internal class Person
{
    [DataMember]
    internal string id;

    [DataMember]
    internal string name;

    [DataMember]
    internal string type;

    [DataMember]
    internal Activities activities;
}

[DataContract]
internal class Activities
{
    [DataMember(Name = "data")]
    internal List<Activity> activity;
}

[DataContract]
internal class Activity
{
    internal string name;
}

当我从WCF方法返回人员列表时,JSON响应如下所示

[{ “活动”:{ “数据”:[{}]}, “ID”: “1234”, “姓名”: “约翰”, “类型”: “用户”},{ “活动”: { “数据”:[{}]}, “ID”: “1234”, “姓名”: “约翰”, “类型”: “用户”}]

有关如何获取“id”(动态)作为每个内部JSON对象的键的任何建议,并且对于项目集合而不是[]有{}括号?

1 个答案:

答案 0 :(得分:1)

DataContractJsonSerializer(DCJS)只能序列化(和反序列化)遵循已定义模式的对象图。您要序列化的数据不会这样做,因此DCJS不能直接用于此。

然而,您可以使用的一件事是无类型的JSON支持,您可以从http://wcf.codeplex.com的codeplex项目获得(#34; WCF支持jQuery&#34;下载)。您可以在codeplex网站或http://blogs.msdn.com/b/carlosfigueira/archive/2010/10/29/working-with-untyped-json-in-a-wcf-service.aspx找到更多信息。

下面的代码显示了如何以您想要的格式序列化数据;使用codeplex项目(WebHttpBehavior3)中的新行为,您可以将JsonObject类作为操作的返回类型。

public class StackOverflow_6990927
{
    [DataContract]
    internal class Person
    {
        [DataMember]
        internal string id;
        [DataMember]
        internal string name;
        [DataMember]
        internal string type;
        [DataMember]
        internal Activities activities;
    }
    [DataContract]
    internal class Activities
    {
        [DataMember(Name = "data")]
        internal List<Activity> activity;
    }
    [DataContract]
    internal class Activity
    {
        [DataMember]
        public string name;
    }
    public static void Test()
    {
        Activities noActivities = new Activities { activity = new List<Activity>() };
        Activities someActivities = new Activities
        {
            activity = new List<Activity>
            {
                new Activity { name = "hiking" },
            }
        };
        Person[] people = new Person[]
        {
            new Person { id = "22877", name = "Foo Bar", type = "user", activities = noActivities },
            new Person { id = "405564", name = "Bar Foo", type = "user", activities = someActivities },
        };
        JsonObject jo = new JsonObject(people.Select(x => new KeyValuePair<string, JsonValue>(x.id, JsonValueExtensions.CreateFrom(x))));
        Console.WriteLine(jo);
    }
}