hoping someone can lend a hand... I am trying to convert JSON to a DataSet, using the below example, but am having problems. I've validated that the JSON is correct, used a method as suggested by Kent. Thanks for your time and help!
The following is my JSON:
{"jsonData":[{"item1":"one"},{"item2":"two"}]}
Here's my webservice 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 + "!";
}
}
Here's one of my error outputs:
d: "ERROR: Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: S. Path '', line 0, position 0..."
Which version are you using? since I was getting a different error (Json.net 4.5). I have done the following and the exception has gone (basically passing the root element name).
Edit: Added the complete code
string jsonData = "{\"jsonData\":[{\"item1\":\"one\"},{\"item2\":\"two\"}]}";
XmlDocument xd = new XmlDocument();
//xd = (XmlDocument)JsonConvert.DeserializeXmlNode(jsonData.ToString()); //Throws exception "This document already has a 'DocumentElement' node."
xd = (XmlDocument)JsonConvert.DeserializeXmlNode(jsonData.ToString(), "jsonData");
DataSet ds = new DataSet();
ds.ReadXml(new XmlNodeReader(xd));
Please let me know if this is not solving your problem.
Solved it with an update to my c# webservice method.
JSON that is passed in looks like the following:
'{"data":{"jsonData":[{"id":"1","name":"Alan","url":"http://www.google.com"},{"id":"2","name":"Louis","url":"http://www.yahoo.com"}]}}'
and the c# webservice method looks like the following:
[WebMethod]
public string myUpdate(object data)
{
try
{
string json = JsonConvert.SerializeObject(data);
XmlDocument xd = new XmlDocument();
xd = (XmlDocument)JsonConvert.DeserializeXmlNode(json, "jsonData");
DataSet ds = new DataSet();
ds.ReadXml(new XmlNodeReader(xd));
return "success"; //return ds.Tables[0].Rows[0][2].ToString(); //just to test
}
catch (Exception e)
{
return "ERROR: " + e + "!";
}
}