JSON to DataSet using Json.NET

馋奶兔 提交于 2019-12-13 19:35:25

问题


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..."


回答1:


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.




回答2:


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 + "!";
            }
        }


来源:https://stackoverflow.com/questions/13589675/json-to-dataset-using-json-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!