如何在WCF休息服务中格式化json响应

时间:2014-02-03 07:31:46

标签: c# wcf rest object

我正在构建一个必须返回json响应的服务:

  

{“内容”:{“API”:“某些API”,“DisplayVersion”:“1.0”,“版本”:1},“状态”:“确定”}

我发现很难按照我想要的方式格式化它。我正以这种方式得到回应:

  

{“API”:“某些API”,“DisplayVersion”:“1.0”,“版本”:“1”}

以下是我的相同代码:

  [WebInvoke(Method = "GET", BodyStyle =
 WebMessageBodyStyle.WrappedRequest, RequestFormat =
 WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json,
 UriTemplate = "")]

         public Info GetSystemInfo()
         {
                 return new Info()
                 {
                     API = "Some API",
                     DisplayVersion = "1.0",
                     Version = "1"
                 };

         }

 [DataContract]
   public class Info
     {
         [DataMember]
         public string API { get; set; }
          [DataMember]
         public string DisplayVersion { get; set; }
          [DataMember]
          public string Version { get; set; }
     }

我试着像这样构建我的类:

   [DataContract]
    public class Info
    {
        [DataMember]
        public class Content
        {
            [DataMember]
            public string API { get; set; }
            [DataMember]
            public string DisplayVersion { get; set; }
            [DataMember]
            public string Version { get; set; }
        }

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

我应该怎么做呢?

1 个答案:

答案 0 :(得分:2)

尝试按照以下方式构建类:

[DataContract]
public class Info
{
    [DataMember]
    public Content Content { get; set; }
    [DataMember]
    public string Status { get; set; }
}

public class Content
{
    [DataMember]
    public string API { get; set; }
    [DataMember]
    public string DisplayVersion { get; set; }
    [DataMember]
    public int Version { get; set; }
}

编辑:使用信息:

    Info info = new Info() 
    { 
        Status = "OK", 
        Content = new Content() { API = "Some Api", DisplayVersion = "1.0", Version = 1 } 
    };