我收到第三方的JSON回复,我无法控制。有时这个响应会在字符串的末尾抛出非法字符。这是一个正确的例子。
{
"result": [
{
"parent": "",
"made_sla": "true",
"caused_by": "",
"watch_list": "",
"upon_reject": "cancel",
"sys_updated_on": "2016-09-13 19:00:01",
"approval_history": "",
"category": "SPIN Station"
}
]
}
错误字符串的示例。在这里你可以看到它最后抛出额外的逗号而不是关闭。
{
"result": [
{
"parent": "",
"made_sla": "true",
"caused_by": "",
"watch_list": "",
"upon_reject": "cancel",
"sys_updated_on": "2016-09-13 19:00:01",
"approval_history": "",
"category": "SPIN Station"
}
],
这是我在c#中的代码。在反序列化之前,任何人都可以告诉如何在下面的代码中的响应值字符串中用右括号替换非法逗号
WebRequest req = WebRequest.Create(@"https://aaaa.service-now.com/api/now/table/incident?sysparm_query=sys_updated_onBETWEENjavascript:gs.dateGenerate('2016-09-10','00:00:00')@javascript:gs.dateGenerate('2016-09-13','23:59:59')");
req.Method = "GET";
req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("username:Password"));
req.ContentType = "application/xml";
HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
var responseValue = string.Empty;
using (var responseStream = resp.GetResponseStream())
{
if (responseStream != null)
using (var reader = new StreamReader(responseStream))
responseValue = reader.ReadToEnd();
}
JavaScriptSerializer ser = new JavaScriptSerializer();
ser.MaxJsonLength = 2147483647;
ser.RegisterConverters(new List<JavaScriptConverter> { new ResultConverter() });
RootObject ro = ser.Deserialize<RootObject>(responseValue);
答案 0 :(得分:0)
我看到你正在连接到ServiceNow。如果你收到格式错误的JSON字符串,这很奇怪 - 我会用hi.service-now.com提出一张票
如果你确实需要纠正你的一面,那么在反序列化之前操纵你的responseValue。
if (responseValue.Substring(responseValue.Length-2, 2)=="],") {
responseValue = responseValue.Remove(str.Length -1, 1) + "}";
}
P.S。我还没有测试过 - 你需要仔细查看输入的JSON字符串,以确保没有拖尾空格。