【问题标题】:after parsing a value an unexpected character was encountered: C解析值后遇到意外字符:C
【发布时间】: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 字符串,你的不是。

标签: c# json


【解决方案1】:

我正在尝试反序列化 JSON 数据下面是 json 数据的结构

不,不是。那不是有效的 JSON。错误正是它所说的,有些引号没有正确转义,所以你有一个悬空的“C”,它不是有效的 JSON。

我不知道该告诉你什么。您的代码可能没问题(没看过),您需要修复您的数据,使其成为有效的 JSON。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-09
    • 2016-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多