0

I am using the wdcalendar with asp.net. After getting the records from the database I need to return a JSON string back to the page. I have the DataTable which contains the records from the DB but I am not sure how to convert it to this exact format:

{ 
  "end" : "09/29/2013 23:59",
  "error" : null,
  "events" : [ [ 1,
        "test",
        "09/26/2013 08:11",
        "09/26/2013 08:08",
        0,
        0,
        0,
        "1",
        1,
        "loca",
        ""
      ],
      [ 2,
        "test2",
        "09/27/2013 08:11",
        "09/27/2013 08:08",
        0,
        0,
        0,
        "1",
        1,
        "loca",
        ""
      ]
    ],
  "issort" : true,
  "start" : "09/23/2013 00:00"
}

I added a new line to show the different data which contains two rows from the database and then at the end there is additional info appended to the data which is the last line shown above.

I am hoping there is a better way then building the string manually.

Thanks.

3 Answers 3

2

Try like this

 public class RootObject
 {
public string end { get; set; }
public object error { get; set; }
public List<List<object>> events { get; set; }
public bool issort { get; set; }
public string start { get; set; }
}

Create a Object and set the properties ... you will get all the details then put it in datatable ...

   Copy paste your json string it will generate the class 

http://json2csharp.com/

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

Comments

1

use this,

public string GetJson(DataTable dt)
{
    System.Web.Script.Serialization.JavaScriptSerializer serializer = new 

    System.Web.Script.Serialization.JavaScriptSerializer();
    List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
    Dictionary<string, object> row = null;

    foreach (DataRow dr in dt.Rows)
    {
        row = new Dictionary<string, object>();
        foreach (DataColumn col in dt.Columns)
        {
            row.Add(col.ColumnName.Trim(), dr[col]);
        }
        rows.Add(row);
    }
    return serializer.Serialize(rows);
}

or using JSON.NET.

string json = JsonConvert.SerializeObject(table, new Serialization.DataTableConverter());
var o = JsonConvert.DeserializeObject<DataTable>(json, new Serialization.DataTableConverter());

1 Comment

Your method is adding a the column names to the final string. Also there is missing the last row.
0

Would it help you convince your bosses to install a library if it's Microsoft's AJAX extensions for .NET 2.0?

Included in them is System.Web.Script.Serialization.JavascriptSerializer, which is used in Step 4 of the last link in your post.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.