16

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

elpidaguy
  • 624
  • 1
  • 11
  • 25
  • You could do `.Replace` on JSONresult and replace all `"\u0022"` with `""` – pacukluka May 18 '20 at 13:52
  • Maybe the following link can help you: [convert datatable to json in c-sharp](https://stackoverflow.com/questions/17398019/convert-datatable-to-json-in-c-sharp)? I think the problem is that you directly pass your datatable object to the serializer. – rekcul May 18 '20 at 13:53
  • @LukaKostic it will work for "" but what if there are different characters? – elpidaguy May 18 '20 at 13:54
  • If I may ask, what functional problem is this causing? Will something downstream fail? Or is it a case of human readability? – George Kerwood May 18 '20 at 13:54
  • 1
    Read the docs about: [How to serialize and deserialize (marshal and unmarshal) JSON in .NET](https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to), especially in relation to the non-ASCII char *treatment* and Encoding. – Jimi May 18 '20 at 13:55
  • that look like you should trim all values before serialize or trim should be part of serialize (there is example https://stackoverflow.com/a/19272300/5888230) – kalit May 18 '20 at 13:55
  • 2
    It looks like you've got a JSON string which itself encodes a JSON string (`\u0022` is a quote character). Chances are that you should just `return Json(new { JSONresult = dt })` – canton7 May 18 '20 at 13:57
  • is the double serialisation intended? – Drag and Drop May 18 '20 at 13:58
  • And the expected result is an invalid Json `"jsoNresult": "[{"` … `"}]"` ? Do you want `"jsoNresult": [{` … `}]}` where jsoNresult is a table of object? And `Formatting.Indented` is about intending it has no power over double quote. It only try to make a json pretty by adding tabs and new line – Drag and Drop May 18 '20 at 14:05
  • 2
    Looks like you are double-serializing your JSON along the lines of [JSON.NET Parser *seems* to be double serializing my objects](https://stackoverflow.com/q/25559179/3744182) -- maybe `System.Text.Json` doesn't support `DataTable`? So, don't do that. If you want to use Json.NET in ASP.NET Core 3.1 see [Where did IMvcBuilder AddJsonOptions go in .Net Core 3.0?](https://stackoverflow.com/q/25559179/3744182). To return raw, serialized JSON without replacing the serializer see [Return “raw” json in ASP.NET Core 2.0 Web Api](https://stackoverflow.com/q/48336680/3744182). – dbc May 18 '20 at 14:57
  • 1
    Possible duplicate of [Invalid format with Json when converting DataTable with Json.Net](https://stackoverflow.com/q/19156485/10263) – Brian Rogers May 18 '20 at 15:26
  • Alternatively, you could add a custom `JsonConverter` like the `DataTableConverter` in [Serialize DataSet with current version of System.Text.Json.JsonSerializer](https://stackoverflow.com/q/59780446/3744182). – dbc May 18 '20 at 16:55

2 Answers2

8

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 })
canton7
  • 37,633
  • 3
  • 64
  • 77
  • your answer makes sense but the code is throwing "A possible object cycle was detected which is not supported. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 32." this error – elpidaguy May 18 '20 at 14:46
  • 1
    Interesting, sounds like `Json` found something that Json.net was fine with. I assume you're using asp.net core -- if you are, you can configure it to use Json.net: [see here](https://stackoverflow.com/questions/42290811/how-to-use-newtonsoft-json-as-default-in-asp-net-core-web-api) – canton7 May 18 '20 at 14:48
  • @elpidaguy and everybody else stumbling over this error: Just add `new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects, TypeNameHandling = TypeNameHandling.Objects, NullValueHandling = NullValueHandling.Ignore }` to your `JsonConvert.SerializeObject()` method and the error is gone. – devbf Sep 10 '20 at 06:36
-1

Try encode the serialized object and check it

   string Encodedresult= HttpUtility.JavaScriptStringEncode(JSONresult))
Ranjith.V
  • 316
  • 1
  • 7