我可以帮您进行翻译。以下是需要翻译的内容:
我已经使用JsonLint验证过这个字符串,它是有效的。
WCF接受的非有效字符串(根据JsonLint的说法):
我正在尝试从网站调用我的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库进行序列化。 我正在尝试发送到我的服务的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; }
}
ReserveModel
类(或在客户端上复制它),然后使用Newtonsoft序列化它?刚刚注意到你的最后一次编辑,这让我想起了什么。 - Marcel N.JsonConvert.SerializeObject(obj);
。 - KLIM8D