简体   繁体   中英

How to remove double quotes from a string inside JSON string?

I am getting JSON string request from the server side. That part not handling by my self. They send the request as following (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}

Then I Deserialize using

BV_response _res_pol = JsonConvert.DeserializeObject<BV_response>(policyJson);

Class BV_response

public class BV_response
{
    public int ID { get; set; }
    public string Data { get; set; }
}

Then

string res = _res_pol.Data.Replace("\\", "");
var policyDetails = JsonConvert.DeserializeObject<PolicyData>(res);

Class 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; }
}

For this JSON string I am getting following exception in this line

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.

This is valid JSON, and does not need string manipulation. It's just JSON stored within JSON.

Do not try unescaping JSON yourself. If the JSON is not valid, get it fixed at source.

Your problem is that you are deserializing the inner JSON to a single object, but it is an array.

Instead, deserialize to a List<> or array.

BV_response _res_pol = JsonConvert.DeserializeObject<BV_response>(policyJson);
var policyDetails = JsonConvert.DeserializeObject<List<PolicyData>>(_res_pol.Data);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM