1

I am trying to convert dataset to JSON in .net core 2.0 and am using the below code to do that

return Ok(JsonConvert.SerializeObject(dataset, Formatting.Indented))

and the output I am getting is

"{\n \"DataSet.RemotingVersion\": {\n \"Major\": 2,\n \"Minor\": 0,\n \"Build\": -1,\n \"Revision\": -1,\n \"MajorRevision\": -1,\n \"MinorRevision\": -1\n },\n \"XmlSchema\": \"<?xml version=\\\"1.0\\\" encoding=\\\"utf-16\\\"?>\\n<xs:schema id=\\\"dataset\\\" xmlns=\\\"\\\" xmlns:xs=\\\"http://www.w3.org/2001/XMLSchema\\\" xmlns:msdata=\\\"urn:schemas-microsoft-com:xml-msdata\\\">\\n <xs:element name=\\\"dataset\\\" msdata:IsDataSet=\\\"true\\\" msdata:UseCurrentLocale=\\\"true\\\">\\n <xs:complexType>\\n <xs:choice minOccurs=\\\"0\\\" maxOccurs=\\\"unbounded\\\">\\n <xs:element name=\\\"datatable\\\">\\n <xs:complexType>\\n <xs:sequence>\\n <xs:element name=\\\"cvbf\\\" type=\\\"xs:string\\\" msdata:targetNamespace=\\\"\\\" minOccurs=\\\"0\\\" />\\n </xs:sequence>\\n </xs:complexType>\\n </xs:element>\\n </xs:choice>\\n </xs:complexType>\\n </xs:element>\\n</xs:schema>\",\n \"XmlDiffGram\": \"<diffgr:diffgram xmlns:msdata=\\\"urn:schemas-microsoft-com:xml-msdata\\\" xmlns:diffgr=\\\"urn:schemas-microsoft-com:xml-diffgram-v1\\\" />\"\n}"

Am pretty new to C# development,

  • How to convert it into proper JSON?
  • and Why is it appearing like this?
kongaraju
  • 9,344
  • 11
  • 55
  • 78
  • Try: return Ok(dataset), to set your desired serialization method set it globally in the Global.asax or in the WebApiConfig.cs – Arno Nov 20 '17 at 13:01
  • Does `Newtonsoft.JSON` work with datasets? – Prathik Nov 20 '17 at 13:01
  • @Prathik Jain it does for my REST server. To some extend... one type of refference between 2 DataSets would not transfer. I'll look up what it was and post it here for info – Arno Nov 20 '17 at 13:03
  • What did not work for me when Json Serializing DataSets is: when having 2 DataTables and using DataSet.Relations.Add() on the DataSet the added relation get's lost during serialization/deserialization – Arno Nov 20 '17 at 13:11
  • It looks like you may be double-serializing your `DataSet` along the lines of [JSON.NET Parser *seems* to be double serializing my objects](https://stackoverflow.com/q/25559179/3744182), [`Ok(Object)`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.controllerbase.ok?view=aspnetcore-2.0#Microsoft_AspNetCore_Mvc_ControllerBase_Ok_System_Object_) takes the object to be serialized, not already-serialized JSON. It then serializes the object for you. – dbc Nov 20 '17 at 16:05
  • OK, aside from the double-serialization there is another issue: The version of Json.NET you are using may not support netstandard20 yet -- and netstandard20 is required for `DataSetConverter`. See [serializes a DataSet to JSON on dotnet core 2.0 #1409](https://github.com/JamesNK/Newtonsoft.Json/issues/1409). Support was added on [October 1](https://github.com/JamesNK/Newtonsoft.Json/commit/ab3315f1d5e57c70203c904be79d8e951bf09794) and so is not in the latest release, [10.0.3](https://github.com/JamesNK/Newtonsoft.Json/releases/tag/10.0.3). – dbc Nov 20 '17 at 22:03

2 Answers2

3

You have two problems here:

  1. You seem to be double-serializing your dataset in the manner described in JSON.NET Parser seems to be double serializing my objects. First you manually serialize your returned object to a string, then call Ok(object) which also serializes the object passed in (i.e. the JSON string), resulting in a nested serialization.

    The solution is not to do this. Let the framework serialize your object for you by simply doing return Ok(dataset);

  2. Update. Json.NET 11.0 Release 1 supports .NET Standard 2.0, so serialization for DataSet and DataTable are now possible in .Net core with this and later versions. You need to upgrade to this or a subsequent version.

    Original answer. Your second problem is that you are trying to serialize a DataSet with Json.NET in .Net core using Json.NET 10.0.3 or earlier -- and unfortunately doing so is not yet supported. As explained in Issue #1409: serializes a DataSet to JSON on dotnet core 2.0 and Issue #1383: .Net core build doesn't include DataTableConverter, this release of Json.NET targets netstandard 1.3 while DataSet and DataTable were introduced in a netstandard 1.5. Thus this version has no built-on logic to serialize these types in .Net core.

    So, what are your options using this version? Firstly, Json.NET is licensed under the MIT License so you could copy its versions of DataSetConverter and DataTableConverter, include them in your project, and add them to JsonSerializerSettings.Converters. The question JsonSerializerSettings and Asp.Net Core shows how settings can be customized in ASP.NET Core.

    Secondly, you could convert your DataSet to a DTO and return that instead. For instance, the following extension methods convert any DataSet to a Dictionary<string, List<Dictionary<string, object>>>, which is serializable by Json.NET:

    public static class DataSetExtensions
    {
        public static List<Dictionary<string, object>> ToDictionaryList(this DataTable table)
        {
            if (table == null)
                return null;
            return table.Rows.Cast<DataRow>()
                .Select(r => table.Columns.Cast<DataColumn>().ToDictionary(c => c.ColumnName, c => r[c]))
                .ToList();
        }
    
        public static Dictionary<string, List<Dictionary<string, object>>> ToDictionary(this DataSet set)
        {
            if (set == null)
                return null;
            return set.Tables.Cast<DataTable>()
                .ToDictionary(t => t.TableName, t => t.ToDictionaryList());
        }
    }
    

    Even better, create a strongly-typed model to return. (If you are also serializing to XML then this is the better solution since XmlSerializer does not support serialization of dictionaries.)

dbc
  • 104,963
  • 20
  • 228
  • 340
  • 1
    Thanks a lot, it really helpful, I finally fixed my code and it saved me lot of time and research. Especially the links worth million thanks. – kongaraju Nov 21 '17 at 06:41
2

As of 25/04/2018. I had exactly same problem. Download latest version of Newtonsoft. I upgraded to 11.0.2. It now works with ASP Core 2. Datasets get converted to JSON.

AlanM
  • 41
  • 4