DanCZ
DanCZ

Reputation: 313

System.OutOfMemoryException with JSON.NET

Tried this with JSON.NET 6.0

DataSet ds = Newtonsoft.Json.JsonConvert.DeserializeObject<DataSet>
("{\"tab1\":[{\"col1\":\"val1\"}]}"); // OK

DataTable dt = Newtonsoft.Json.JsonConvert.DeserializeObject<DataTable>
("{\"col1\":\"val1\"}"); // System.OutOfMemoryException

why?

thank you

Upvotes: 3

Views: 2103

Answers (3)

Dilip Langhanoja
Dilip Langhanoja

Reputation: 4525

I have over come with this issue by creating JsonSerializer object. My code is as given below.

using (StreamReader r = new StreamReader(yourfilePath))
{
    using (JsonReader reader = new JsonTextReader(r))
    {
         JsonSerializer serializer = new JsonSerializer();
         T lstObjects =  serializer.Deserialize<T>(reader);
    }
}

Here yourfilePath :- is your file current full path T :- is your object name, whether it could be Dataset, DataTable or any custom Object.

Upvotes: 0

Brian Rogers
Brian Rogers

Reputation: 129667

The JSON in your second example represents a only a single row of data, not a DataTable. A DataTable is an ordered collection of DataRows, therefore it needs to have square brackets in the JSON. Try it like this instead:

string json = "[{\"col1\":\"val1\"}]";
DataTable dt = JsonConvert.DeserializeObject<DataTable>(json);

I am not sure why you are getting an OutOfMemoryException; I get a JsonSerializationException when I try it, as I would expect. Perhaps this was a bug that was fixed in the most recent version of Json.Net.

Upvotes: 1

dekajoo
dekajoo

Reputation: 2102

IMO it's a bug, But if you want to deserialize DataSet or DataTable this might help you.

Upvotes: 1

Related Questions