Tiago
Tiago

Reputation: 35

JSON.NET "System.OutOfMemoryException" when deserializing into a DataSet

Very new to C# and JSON. I have been struggling with this problem for about a day and can't figure it out.

JSONLint states both JSON strings are valid.

Trying to deserialize the following

{"items":[{"id":"1122267","quantity":"1","bundle":"1"}],"seconds_ago":"1"}

throws the exception

An unhandled exception of type 'System.OutOfMemoryException' occurred in Newtonsoft.Json.dll

If I try

{"items":[{"id":"1122267","quantity":"1","bundle":"1"}]} 

it works.

I'm reading the JSON string from a textbox and then deserializing using the following

string json = textBox1.Text;
DataSet dataSet = JsonConvert.DeserializeObject<DataSet>(json);

Upvotes: 1

Views: 5798

Answers (2)

JW Lim
JW Lim

Reputation: 1814

I'm not at all familiar with DataSet, but after playing around with it a bit, I think I've found the reason. According to the documentation:

The DataSet consists of a collection of DataTable objects

Because a DataSet is a collection of objects, you can only deserialize a collection (array) into it. So,

{"items":[{"id":"1122267","quantity":"1","bundle":"1"}],"seconds_ago":"1"}

will not work, because it contains one collection (of items) and one property (seconds_ago). On the other hand,

{"items":[{"id":"1122267","quantity":"1","bundle":"1"}]} 

works, because it only contains one collection.

Therefore, if you really want to deserialize your json string into a DataSet, you should do this instead:

{
    "objects": [
        {
            "items":[{"id":"1122267","quantity":"1","bundle":"1"}],
            "seconds_ago":"1"
        }
    ]
} 

You should really consider deserializing into a C# object though, which in my opinion is less complicated and easier to handle:

public class RootObject
{
    public List<Item> items { get; set; }
    public string seconds_ago { get; set; }
}

public class Item
{
    public string id { get; set; }
    public string quantity { get; set; }
    public string bundle { get; set; }
}

RootObject deserializedObject = JsonConvert.DeserializeObject<RootObject>(json);

Upvotes: 4

JK.
JK.

Reputation: 21808

The DataSet class does not have a property seconds_ago or items. So therefore

DataSet dataSet = JsonConvert.DeserializeObject<DataSet>(json);

Will never work because you cannot convert that particular json string to a DataSet

Upvotes: -1

Related Questions