Home »

Convert Dataset to JSON String and vice versa using Json.NET

Sometimes it's more convenient to use a string rather a dataset. So if you handle a dataset, you must convert it to string. The best way to do that is to convert it to json string.
And then, after you finish everything, you'll need to convert that string back to dataset so that you can save the result into the database or display it.
In this entry I'll show you the easiest way to do that using Json.NET
In this project I use .NET 2.0. If you want to use .NET 3.5 all you have to do is remove reference Newtonsoft.Json.Net20 and add the Newtonsoft.Json.Net35 in bin folder.

Dataset to Json String

StringWriter sw = new StringWriter();
ds.WriteXml(sw, XmlWriteMode.IgnoreSchema);
XmlDocument xd = new XmlDocument();
xd.LoadXml(sw.ToString());

string jsonText = JsonConvert.SerializeXmlNode(xd);
txtResult.Text = jsonText;
First, if you want to convert DataSet to Json String you have to convert DataSet to XMLDocument (Here I use StringWritter).
When you've already added Newtonsoft.Json.Net to you References, you can use JsonConvert to convert between JSON and XML. If you want to convert o JSON String, use SerializeXmlNode. This method takes an XmlNode and serializes it to JSON text.

Json String to Dataset

XmlDocument xd = new XmlDocument();
xd = (XmlDocument)JsonConvert.DeserializeXmlNode(txtStr.Text);
DataSet ds = new DataSet();
ds.ReadXml(new XmlNodeReader(xd));

//Once you have your dataset, you can use it to save data into database or display it
gvCustomers.DataSource = ds.Tables[0];
gvCustomers.DataBind();
To do this, we use method DeserializeXmlNode on JsonConvert. This method takes JSON text and deserializes it into a XmlNode. And we can easily convert it into DataSet using method ReadXml.

So, I think that's enough for this entry. If you want to find out more, visit Json.NET to download the full project as well as documentations.

Hope this entry help you!
If you found any mistake or error in this entry, please let me know. I'll try to fix that a.s.a.p.
Any solution is highly appreciated!

-Share2Learn-

17 comments:

  1. XmlDocument xd = new XmlDocument();
    xd = JsonConvert.DeserializeXmlNode(str /*str is json string*/);
    DataSet ds = new DataSet();
    ds.ReadXml(new XmlNodeReader(xd));

    when i execute the above code i got the following error.

    Cannot add a nested relation or an element column to a table containing a SimpleContent column.

    ReplyDelete
  2. I think your xml might contain an element which has both text children and other element children.

    You can find it here: http://msdn2.microsoft.com/en-us/library/zx8h06sz.aspx

    Kent

    I didn't blog here anymore, but glad to know that it might help someone ^^

    ReplyDelete
  3. XmlDocument xd = new XmlDocument();
    xd = JsonConvert.DeserializeXmlNode(str /*str is json string*/);
    DataSet ds = new DataSet();
    ds.ReadXml(new XmlNodeReader(xd));

    xd = (XmlDocument)Json.........

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete
  5. When I am converting DataSet to JsonText String then some empty Columns of the table has been converted in JsonText but some of them does not converted in JsonText String .

    Please give any solution of this problem .

    ReplyDelete
  6. What do you mean? Did you get any error message? Please give more details! ^^

    ReplyDelete
  7. I am getting dataset which has 8 tables, if any table has some empty column in particular row , then that empty field can not be serialized
    but some of empty fields has serialized . please give me the correct solution of this problem.

    ReplyDelete
  8. ASAIK, if the column is empty, the value in the json string is empty, you can use this site to validate your returned json string: http://jsonlint.com/

    ReplyDelete
  9. This comment has been removed by the author.

    ReplyDelete
    Replies
    1. empty columns are not serialize in json string.

      Delete
  10. If your json string is valid, then the function is correct :)
    Enjoy

    ReplyDelete
  11. sorry kent,
    I have used another method in which json string is valid but in your method , empty columns are not serialize in json string.

    ReplyDelete
  12. Hi kent I have used another method to serialize dataset to json string, this json string is valid .

    my question is now

    How to deserialize json string to dataset ???

    ReplyDelete
  13. I already posted it in the post, please check above!

    ReplyDelete
    Replies
    1. This does not eliminate empty fields of dataset and working well........for "dataset to json string"

      StringWriter sw = new StringWriter();
      ds.WriteXml(sw, XmlWriteMode.WriteSchema);
      XmlDocument xd = new XmlDocument();
      xd.LoadXml(sw.ToString());
      String jsonText = JsonConvert.SerializeXmlNode(xd);

      string jsonText = JsonConvert.SerializeXmlNode(xd);
      txtResult.Text = jsonText;

      Delete
  14. but this has eliminate empty columns at the time of serialization , I need to all the columns in the serializataion and deserialization process.

    ReplyDelete
  15. Hi Kent, hoping you can lend a hand... I am trying to convert JSON to a DataSet, using your example, but am having problems.

    I'm using your JSON to DataSet conversion. The following is my JSON:
    {"jsonData":[{"item1":"one"},{"item2":"two"}]}

    Here's my webservice in C# code:
    [WebMethod]
    public string setWorkOrdersUpdated(object jsonData)
    {
    try
    {
    XmlDocument xd = new XmlDocument();
    xd = (XmlDocument)JsonConvert.DeserializeXmlNode(jsonData.ToString());
    DataSet ds = new DataSet();
    ds.ReadXml(new XmlNodeReader(xd));
    return "success";
    }
    catch (Exception e)
    {
    return "ERROR: " + e + "!";
    }
    }

    ReplyDelete