user130622
user130622

Reputation: 53

Converting JSON string to DataTable

I know this kind of question has been asked before but I cannot seem to find anything that is working.

I am trying to convert a JSON string to a DataTable, or any other form that I can work with on C#.

Here is an example of the JSON file I receive:

{ "DatabaseName" : {"Employees": [{"Full-Name":"John Smith","Address":["123 Main St", "Apt 202"],"City":"NYC"}]}}

I have tried different things, but I either get an empty DataTable, or many different errors.

Object jObject = JsonConvert.DeserializeObject<JObject>(Response.Content);
DataTable dsResult = JsonConvert.DeserializeObject<DataTable>(jObject.ToString());

Gives me:

Unexpected JSON token when reading DataTable. Expected StartArray, got StartObject. Path '', line 1, position 1.

Any help would be appreciated.

I have used JSON 2 C# to create a class as well, and trying to convert it using

JsonConvert.DeserializeObject<Employees>(Response.Content);

However the classes do not allow me to create a variable public string Full-Name since I cannot use a - when creating a variable.

Is there a workaround for this?

Upvotes: 0

Views: 7720

Answers (2)

NeonBoxx
NeonBoxx

Reputation: 143

That JSON is invalid, use this to check: http://jsonlint.com/

should be something like

{
    "DatabaseName": "Employees",
    "Rows": [
        {
            "FullName": "John Smith",
            "Address": [
                "123 Main St",
                "Apt 202"
            ],
            "City": "NYC"
        }
    ]
}

Upvotes: 1

C1rdec
C1rdec

Reputation: 1687

Use Json 2 C# to create your class and like @Plutonix said look here for the Data Table.

Upvotes: 0

Related Questions