How to have JSON String without characters like '\u0022' or '\' while converting DataTable to JSON String using NewtonSoft in .Net Core 3.1

Viewed 16129

I am writing a simple API in .net core 3.1. To convert my DataTable to JSON String I am using NewtonSoft Library with following code:

string JSONresult = JsonConvert.SerializeObject(dt, Formatting.Indented);
return Json (new { JSONresult });

The output I am getting is JSON String but it has so many characters like '\u0022' which I know its for double quotes.

{"jsoNresult":"[\r\n  {\r\n    \u0022ID\u0022: 2,\r\n    \u0022FunctionalityName\u0022: \u0022User Upload\u0022,\r\n    \u0022FunctionalityDescription\u0022: \u0022For Bulk Uploading User At Once\u0022,\r\n    \u0022TableName\u0022: \u0022tablename\u0022,\r\n    \u0022ValidationSP\u0022: \u0022user_Validate\u0022,\r\n    \u0022InsertSP\u0022: \u0022Insert_User\u0022\r\n  }\r\n]"}

All I Want is:

{"jsoNresult":"[{"ID": "2","FunctionalityName": "User Upload","FunctionalityDescription": "For Bulk Uploading User At Once","TableName": "tablename","ValidationSP": "user_Validate","InsertSP": "Insert_User"}]"}

I am new in c#, but having previously worked on Flask or even spring boot, they returns clear json string.

So How do I achieve what I want in .net core 3.1. PS: I know the use of Formatting.Indented , I can have serialized string with or without it

2 Answers

The first clue is that your JSON string

{"jsoNresult":"[\r\n  {\r\n    \u0022ID\u0022: 2,\r\n    \u0022FunctionalityName\u0022: \u0022User Upload\u0022,\r\n    \u0022FunctionalityDescription\u0022: \u0022For Bulk Uploading User At Once\u0022,\r\n    \u0022TableName\u0022: \u0022tablename\u0022,\r\n    \u0022ValidationSP\u0022: \u0022user_Validate\u0022,\r\n    \u0022InsertSP\u0022: \u0022Insert_User\u0022\r\n  }\r\n]"}

Looks like it contains a JSON string: [\r\n {\r\n \u0022ID\u0022 looks a lot like JSON, bearing in mind that \u0022 is the quote " character (the ascii character with value 0x22 is ").

From this we can conclude that the code:

string JSONresult = JsonConvert.SerializeObject(dt, Formatting.Indented);
return Json (new { JSONresult });

Is actually encoding the JSON twice. Once is obviously the JsonConvert.SerializeObject, but the other is probably the Json object.

From this it's fairly clear that Json expects an object to serialize, and it will do the serialization itself. You don't need to pass it a serialized string.

This is supported by the documentation, which says:

Creates a JsonResult object that serializes the specified data object to JSON.

So try:

return Json(new { JSONresult = dt })

Try encode the serialized object and check it

   string Encodedresult= HttpUtility.JavaScriptStringEncode(JSONresult))
Related