简体   繁体   中英

Newtonsoft DeserializeObject error after going from .Net Framework 4.6.1 Console App to Core 2.0 console App

Using .Net Framework 4.6.1 this works perfectly:

private DataTable GetRESTData(string pUri)
{
    var json = ReadFromUri(pUri);
    var obj = JsonConvert.DeserializeObject(json);

    string StrContent = ((Newtonsoft.Json.Linq.JObject)obj).Last.ToString();
    StrContent = StrContent.Substring(9, StrContent.Length - 9);

    DataTable dt = JsonConvert.DeserializeObject<DataTable>(StrContent);
    return dt;
}

This also works:

DataTable dt = (DataTable)JsonConvert.DeserializeObject(StrContent.Substring(9, StrContent.Length - 9), (typeof(DataTable)));

But I can't find anything that works on CORE 2.0 Console App, I always get:

Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON array (eg [1,2,3]) into type 'System.Data.DataTable' because the type requires a JSON object (eg {"name":"value"}) to deserialize correctly.
To fix this error either chang...

If I watch the string StrContent.Substring(9, StrContent.Length - 9) as JSON or as a string, it's perfectly formatted.

I installed NewtonSoft from Nuget Package Manager.

EDIT: I'm using Visual Studio 2017. If I run this on project with Framework 4.6.1 it works perfectly, Project with CORE 2.0 shows the error I posted above.

The current stable vesion of Newtonsoft.Json library does not support serializing DataSets/DataTables as in the full .NET version.

This is because the library (version 10.0.3) targets the NETStandard 1.3, but the DataSet/DataTable support was added on Net Core 2.0.

The current beta version targets NetStandard 2.0 and does support serializing datasets, so if you update your reference to use the latest beta package Newtonsoft.Json/11.0.1-beta1 or wait until a stable version is released, you will be able to serialize/deserialize.

You can check by yourself, if you serialize the following DataTable as JSON on .NET core (Newtonsoft.Json/10.0.3):

var dt = new DataTable();
dt.Columns.Add("Column1", typeof(string));
dt.Rows.Add("value");
var json = JsonConvert.SerializeObject(dt);

You will get something like this:

{
  "DataTable.RemotingVersion": {
    "Major": 2,
    "Minor": 0,
    "Build": -1,
    "Revision": -1,
    "MajorRevision": -1,
    "MinorRevision": -1
  },
  "XmlSchema": "<?xml version=\"1.0\" encoding=\"utf-16\"?>\r\n<xs:schema xmlns=\"\" ... </diffgr:diffgram>"
}

But if you target the current beta version (11.0.1-beta1) you get:

[
  {
    "Column1": "value"
  }
]

There is an issue on the library about this 1409

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