c# - 如何从 JSON 字符串中的字符串中删除双引号?
问题描述
我从服务器端收到 JSON 字符串请求。那部分不是我自己处理的。他们发送请求如下(policyJson)
{"Data":"[{\"NAME\":\"BOARD OF INVESTMENT OF SRI LANKA\",\"STARTDATE\":\"\\\/Date(1584210600000)\\\/\",\"ENDDATE\":\"\\\/Date(1615660200000)\\\/\",\"SCOPE\":\"As per the standard SLIC \\\"Medical Expenses\\\" Policy Wordings\",\"DEBITCODENO\":1274}]","ID":200}
然后我反序列化使用
BV_response _res_pol = JsonConvert.DeserializeObject<BV_response>(policyJson);
BV_response类
public class BV_response
{
public int ID { get; set; }
public string Data { get; set; }
}
然后
string res = _res_pol.Data.Replace("\\", "");
var policyDetails = JsonConvert.DeserializeObject<PolicyData>(res);
类PolicyData
public class PolicyData
{
public string NAME { get; set; }
public DateTime STARTDATE { get; set; }
public DateTime ENDDATE { get; set; }
public string SCOPE { get; set; }
public int DEBITCODENO { get; set; }
}
对于这个 JSON 字符串,我在这一行中遇到了以下异常
var policyDetails = JsonConvert.DeserializeObject(res);
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'SHE_AppWS.Models.PolicyData' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path '', line 1, position 1.
解决方案
这是有效的 JSON,不需要字符串操作。它只是存储在 JSON 中的 JSON。
不要尝试自己对JSON 进行转义。如果 JSON 无效,请在源处对其进行修复。
您的问题是您将内部 JSON 反序列化为单个对象,但它是一个数组。
相反,反序列化为一个List<>
或数组。
BV_response _res_pol = JsonConvert.DeserializeObject<BV_response>(policyJson);
var policyDetails = JsonConvert.DeserializeObject<List<PolicyData>>(_res_pol.Data);
推荐阅读
- reactjs - 在 nextjs 中预渲染页面发生错误
- nginx - NGINX SSL handshake error - sslv3 alert certificate expired:SSL alert number 45
- visual-studio - Include compile file (incremental build)
- node.js - How to make a GET request (MongoDB -- Express)?
- mysql - 如何将表名作为参数传递给游标而不以动态方式创建视图
- python - SqlAlchemy:基于货币的金额精度
- vb.net - vb net append list of with item/index list
- ios - 显示 iOS 15 问题的小部件图像。黑色矩形出现/消失在图像上
- ruby-on-rails - 如何在 Rails ActiveRecord 中一次执行多个 JOINS
- node.js - 将 CoseSign1 转换为 JSON