JSON字符串编码两次? [英] JSON string encoded twice?
问题描述
我的Web API(生成JSON的代码)正在生成以下JSON字符串.如果我没记错的话,它似乎已经被编码了两次:
My Web API (code that generates JSON) is generating the following JSON string. It seems, if I am not wrong, that it has been encoded twice:
"\"[{\\\"SportID\\\":1,\\\"SportName\\\":\"Tennis\\\"},{\"SportID\\\":2,\\\"SportName\\\":\\\"Footbal\\\"},{\"SportID\\\":3,\"SportName\":\\\"Swimming\\\"}]\""
Web API代码:
Web API code:
public string JSONTest()
{
List<Sport> sports = new List<Sport>();
sports.Add(new Sport() { SportID = 1, SportName = "Tennis" });
sports.Add(new Sport() { SportID = 2, SportName = "Footbal" });
sports.Add(new Sport() { SportID = 3, SportName = "Swimming" });
try
{
return JsonConvert.SerializeObject(sports);
}
catch (Exception ex) { }
}
Sport
类:
public class Sport { public int SportID { get; set; } public string SportName { get; set; } }
获取JSON的屏幕截图:
Screenshot of getting JSON:
下面的行给我一个错误,我认为是由于两次编码:
The following line gives me an error, I think because of twice encoding:
var JavaScriptSerializerResult = (new JavaScriptSerializer()).Deserialize< List<Sport>>(jsonResponse);
如果尝试此操作,我会得到相同的错误:
I get the same error if try with this:
var jsonConvertResult = JsonConvert.DeserializeObject<List<Sport>>(jsonResponse);
如何修复我的Web API使其不进行两次编码,或者如果这不是问题,那么如何解码此JSON?
How can I fix my Web API to not encode twice, or if that is not the problem, how can I decode this JSON?
推荐答案
我认为您应该尝试JsonConvert.DeserializeObject
反序列化JSON:
I think you should try JsonConvert.DeserializeObject
to deserialize the JSON:
public class Sport
{
// Dummy "Sport" class as it was not mentioned by OP.
public int SportID { get; set; }
public string SportName { get; set; }
}
我将序列化的JSON作为:
I get serialized JSON as:
反序列化它:
string json = JSONTest();
var obj = JsonConvert.DeserializeObject<List<Sport>>(json);
输出:
更新:
根据OP的共享JSON(从服务器接收),可以使用以下方式删除编码:
As per OP's shared JSON (which is being received from server), encoding can be removed by using:
private string RemoveEncoding(string encodedJson)
{
var sb = new StringBuilder(encodedJson);
sb.Replace("\\", string.Empty);
sb.Replace("\"[", "[");
sb.Replace("]\"", "]");
return sb.ToString();
}
通过以下方式反序列化它:
Deserialize it by:
string js = "\"[{\\\"SportID\\\":1,\\\"SportName\\\":\"Tennis\\\"},{\"SportID\\\":2,\\\"SportName\\\":\\\"Footbal\\\"},{\"SportID\\\":3,\"SportName\":\\\"Swimming\\\"}]\"";
string res = RemoveEncoding(js);
var obj = JsonConvert.DeserializeObject<List<Sport>>(res);
这篇关于JSON字符串编码两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!