0

I have a datatable which I am attempting to send to a webpage in the JSON format

{"Heading":[{"value":"someTitle", "id":0, children:[]},...]}

I have attempted to cobble together code in order to do this. The datatable rows contain 3 columns: id, heading and value.

Here is what I have:

JObject ret = JObject.Parse("{ isAdmin: false, data: {} }");

...

var headings = (from row in dt.AsEnumerable()
                select row["Heading"].ToString()).Distinct();

//var jsonResults = JObject.Parse(results);
foreach (var heading in headings.ToArray())
{
    var dArray =
        (from row in dt.AsEnumerable()
         where row["Heading"].ToString() == heading
         select new { id = row["id"], value = row["reportTitle"] }
        ).ToArray();
    var jArr = new JArray(dArray);
    ret["data"][heading] = jArr;
}

The exception I am receiving is

Could not determine JSON object type for type >f__AnonymousType0`2[System.Object,System.Object].

How can I restructure this code to receive the results I need?

3
  • Where do you receive that exception? At the first line above? Commented Feb 26, 2020 at 0:15
  • You need to provide the table structure and query/code that is yielding the dt DataTable. Otherwise it's hard to know if your field names or object structure are correct. Commented Feb 26, 2020 at 0:20
  • @JordanRieger "The datatable rows contain 3 columns: id, heading and value." Commented Feb 26, 2020 at 15:06

1 Answer 1

3

You are attempting to put an array of anonymous objects directly into a JArray. This will not work. Instead, put your row data into JObjects and add those to the JArray. You can do that by changing this line:

select new { id = row["id"], value = row["reportTitle"] }

to this:

select new JObject(
           new JProperty("id", row["id"]), 
           new JProperty("value", row["reportTitle"])
       )

Fiddle: https://dotnetfiddle.net/x5KqXy

Sign up to request clarification or add additional context in comments.

2 Comments

That worked perfectly. Thank you. It was the one last piece that I needed.
No problem; glad I could help.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.