【发布时间】:2017-12-11 13:52:29
【问题描述】:
我正在尝试反序列化 JSON 数据下面是 json 数据的结构
[{"empcode":"e123","joining_date":"2017-10-31T00:00:00","pfno":"pf232323","Rating":"A","emp_Type":"full","Project_name":"abcd 123bcc "C""}]
Project_name 由 json 中的双引号字符组成
我正在使用 newtonsoft.json 对 JSON 数据进行序列化和反序列化
当我将 JSON 数据反序列化为数据表时,在解析值后出现错误,遇到意外字符:C.
public static datatable getDataFromServer(string url)
{
HttpWebRequest req = null;
HttpWebResponse res = null;
//string url = url1 + date;
//Console.WriteLine(url);
req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "GET";
req.ContentType = "application/json; charset=utf-8";
// req = AddProxy(req);
res = (HttpWebResponse)req.GetResponse();
Stream responseStream = res.GetResponseStream();
var streamReader = new StreamReader(responseStream);
string txt = streamReader.ReadToEnd();
txt = txt.Replace("\\", "").Replace("/", "");
// txt = txt.Replace("\\", "");
// txt = txt.Replace(@"\", "");
txt = txt.Remove(0, 1);
txt = txt.Remove(txt.Length - 1, 1);
DataTable ds = GetDeserializedFrmJson(txt);
streamReader.Close();
streamReader.Dispose();
responseStream.Close();
responseStream.Dispose();
return ds;
}
public static DataTable GetDeserializedFrmJson(string data)
{
DataTable dt = (DataTable)JsonConvert.DeserializeObject(data, (typeof(DataTable)));
return dt;
}
【问题讨论】:
-
嗯,是的,这是无效的 JSON。您在一个值中有“C”,而引号没有被转义。诚然,这可能是因为您要手动删除所有斜杠 - 为什么要这样做?我强烈建议您不要再弄乱您收到的 JSON。
-
接下来,
GetDeserializedFrmJson是什么?请提供minimal reproducible example(只需对 JSON 进行硬编码)。如果您没有使用 JSON 解析器库来解析 JSON,而是依赖于手写代码,我强烈建议您立即停止这样做。 -
使用 Newtonsoft.Json;
-
这是您从 Web 请求中收到的原始 JSON 字符串,还是在您刚刚使用
txt = txt.Replace("\\", "")删除了转义引号之后?这也许不是一个好主意。因为"abcd 123bcc \"C\""应该是一个有效的 JSON 字符串,你的不是。