简体   繁体   中英

C# Pass filename as json parameter- Getting error “Unrecognized escape sequence. ”

I want to pass a filepath through JSON. On deserializing I am getting error:

Unrecognized escape sequence. (43): {"Jobtype": "StepBatch","SelectedId": "D:\\Input\\file1.CATPart"}

I have escaped characters but it still shows error...am I missing something here?

string json = "{\"Jobtype\": \"StepBatch\",\"SelectedId\": \"D:\\Input\\file1.CATPart\"}";
var jsonObj = new JavaScriptSerializer().Deserialize<List<Arguments>>(json);

The problem is that the content of your string at execution time is:

{"Jobtype": "StepBatch","SelectedId": "D:\Input\file1.CATPart"}

That's not valid JSON, because of the backslashes in the value for SelectedId . You'd need the JSON to be:

{"Jobtype": "StepBatch","SelectedId": "D:\\Input\\file1.CATPart"}

so your C# would have to be:

string json = "{\"Jobtype\": \"StepBatch\",\"SelectedId\": \"D:\\\\Input\\\\file1.CATPart\"}";

However, given that you're immediately deserializing the JSON anyway, I'd suggest getting rid of the JSON part entirely, and just creating the Arguments values yourself.

If you need to produce JSON, create the right values directly, and then get JavaScriptSerializer (or preferrably Json.NET) to create the JSON for you, instead of hand-coding it.

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