WCF编写嵌套的Json Webservice

时间:2014-12-01 07:27:01

标签: c# asp.net json web-services wcf

我必须在下面nested Json结构的dot net中编写WCF Web服务。我知道如何编写简单的json但不确定是否将它嵌套为`results

{
    "version": 2,


        "results": [{
        "company": "ABC Company Inc.",
        "city": "Sacramento",
        "state": "CA"
    }

    ]
}

我在做的是:

file1.cs

namespace Test
{
    public class file1
    {
        public class child
        {
            [DataMember]
            public string version { get; set; }
        }

        public class parent
        {
            [DataMember]
            public string company { get; set; }

            [DataMember]
            public string city { get; set; }

        }
    }
}

file2.svc.cs

public List<file1> method()
     {


         List<file1.child> result = new List<file1.child>();
         List<file1.parent> result1 = new List<file1.parent>();
         List<file1> final = new List<file1>();
         foreach (DataRow catt1 in dtcategory.Rows)
         {



             result.Add(new file1.child()
             {
                 version= catt1["version"].ToString(),

                });


             result1.Add(new file1.parent() {

                 company= catt1["company"].ToString(),
                 city= catt1["city"].ToString(),


             });
             final.Add(new file1()
             {


             });
              }


         return Add;

     }

请告诉我出错的地方

2 个答案:

答案 0 :(得分:0)

班级结构:

public class class1
{

[DataMember]
public string version {get;set;}

[DataMember]
public List<class2> results {get;set;}

}

public class class2
{

[DataMember]
public string company {get;set;}


[DataMember]
public string city{get;set;}

[DataMember]
public string state {get;set;}


}

答案 1 :(得分:0)

你的问题有点不清楚。但是,如果您询问“我如何设计我的课程file1.childfile1.parent,以便在按DataContractJsonSerializerJson.NET序列化时生成所显示的JSON”,然后你可以这样做:

    public class file1
    {
        [DataContract]
        public class child
        {
            [DataMember(Name="version")]
            public string Version { get; set; }

            [DataMember(Name="results")]
            public List<parent> Results { get; set; }
        }

        [DataContract]
        public class parent
        {
            [DataMember(Name="company")]
            public string Company { get; set; }

            [DataMember(Name="city")]
            public string City { get; set; }

            [DataMember(Name="state")]
            public string State { get; set; }
        }
    }

请注意,鉴于您的班级名称,parent包含child,这是违反直觉的。您可能想要更改这些名称。