WCF HttpPost无效的json字符串

时间:2013-05-27 08:30:52

标签: c# json wcf validation

我正在尝试从网站上调用我的WCF服务上的POST方法。但是,WCF服务抱怨json字符串无效。

WCF服务方法:

[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "reserve/batteries", BodyStyle = WebMessageBodyStyle.Bare)]
public bool ReserveBatteries(ReserveModel values)

从网站调用POST的方法:

var stations = TempData["Stations"];
string jsonStations = JsonHelper.SerializeJson(stations);

HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create("http://localhost:49288/reserve/batteries");

UTF8Encoding encoding = new UTF8Encoding();
string postData = "{\"Stations\": " + jsonStations;
postData += ", \"User\": \"" + User.Identity.Name + "\" }";
byte[] data = encoding.GetBytes(postData);

httpWReq.Method = "POST";
httpWReq.ContentType = "application/json; charset=utf-8";
httpWReq.ContentLength = data.Length;

using (Stream stream = httpWReq.GetRequestStream())
{
      stream.Write(data, 0, data.Length);
}

HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();

string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

我正在使用Newtonsoft json libary来序列化。 我试图发送给我的服务的json字符串是:

{
    "Stations": [
        {
            "BatteryStorages": null,
            "CreatedDate": "2013-06-06T00:00:00+02:00",
            "Description": "Aalborg City",
            "Edges": [],
            "ID": 3,
            "IsActive": true,
            "IsOperational": true,
            "Reservations": [],
            "StationLat": 57.02881,
            "StationLong": 9.91777,
            "StationMaintenances": [],
            "StationType": null,
            "Title": "Aalborg",
            "TypeId": 1,
        }
    ],
    "User": "user1"
}

我已使用JsonLint对此进行了验证,并说它是一个有效的字符串。

WCF接受的无效字符串(根据JsonLint):

{
    "Stations": "[
         {
             BatteryStorages:null,
             CreatedDate:\"/Date(1370469600000+0200)/\",
             Description:\"Aalborg City\",
             Edges:[],
             ID:\"3\",
             IsActive:\"true\",
             IsOperational:\"true\",
             Reservations:[],
             StationLat:\"57.02881\",
             StationLong:\"9.91777\",
             StationMaintenances:[],
             StationType:null,
             Title:\"Aalborg\",
             TypeId:\"1\"
         }
     ]",
     "User": "user1"
}

从WCF抛出的异常:

  

反序列化RestfulAPI.Resources.ReserveModel类型的对象时出错。从命名空间''预期结束元素'Stations'。从命名空间''找到元素'item'。

这怎么可能?为什么WCF抱怨它在jsonlint(和其他人)说它无效时无效。

编辑:

[DataContract]
public class ReserveModel
{
    [DataMember]
    public string Stations { get; set; }
    [DataMember]
    public string User { get; set; }
}

1 个答案:

答案 0 :(得分:5)

问题是您的Model对象格式不正确。

要从JSON创建正确的JSON类,可以使用json2csharp,或者如果有,例如VS2012更新2,则可以复制JSON并将JSON粘贴为类(编辑 - >选择性粘贴> ;将JSON粘贴为类)。

您必须记住,例如,必须以WCF支持的特定方式传递DateTime对象。有关此内容的更多信息,请参见here (msdn - WCF JSON serialization)。要避开此问题,您只需键入变量为string并在以后转换它。

希望这有帮助!