首页 > 解决方案 > 如何从 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.

标签: c#json

解决方案


这是有效的 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);

推荐阅读