6

I am creating a C# Application using Web Services. In my Web Services I'm using a JSONString data. But I'm not able to convert this string into a DataSet.

My JSONString is :

{
    "Table": [
        {
            "DisplayVoucherNumber": "A101239Z",
            "ActualDate": "08/07/2013",
            "AccountName": "shyamal",
            "Pcs": "50",
            "Weight": "500.000"
        }
    ],
    "Table1": [
        {
            "DisplayVoucherNumber": "R101249B",
            "ActualDate": "11/07/2013",
            "AccountName": "vipul",
            "NetWeight": "90.000",
            "Weight": "80.000",
            "Difference": "10.000"
        },
        {
            "DisplayVoucherNumber": "R101249B",
            "ActualDate": "11/07/2013",
            "AccountName": "vipul",
            "NetWeight": "500.000",
            "Weight": "100.000",
            "Difference": "400.000"
        }
    ]
}
shA.t
  • 16,580
  • 5
  • 54
  • 111
Chirag Parmar
  • 1,064
  • 2
  • 13
  • 29

6 Answers6

15

Your question is not very clear. I guess that what you would like to do is get back an object that could be mapped to you data set after deserializtion. Something like

DataSet myDataSet= JsonConvert.DeserializeObject<DataSet>(jsonstring)

And you keep going coding with you dataset. like accessing datatables inside the dataset.

If it's what you want to achieve and don't want to use your own POCO as suggested by previous answers. You might need to create a Typed DataSet before

Given an XML Schema that complies with the XML Schema definition language (XSD) standard, you can generate a strongly typed DataSet using the XSD.exe tool provided with the Windows Software Development Kit (SDK). More info on strongly typed Dataset

This will allow you to use the strongly typed dataset using the Deserialize method.

Bare in mind that you have to mimic your JSon Structure in the XML Schema. in order to have something compatible with your JSon Structure at the end.

rocky
  • 7,506
  • 3
  • 33
  • 48
Oualid KTATA
  • 1,116
  • 10
  • 20
14

As a dynamic C# solution(when you don't know the object structure to deserialize) by using @Dhaval's answer and after invaliding Deserialize<>() method I use below method to do that:

Update: DataSet.ReadXml has some options in reading XML node as XmlReadMode:

private static DataSet ReadDataFromJson(string jsonString, XmlReadMode mode = XmlReadMode.Auto)
{
    //// Note:Json convertor needs a json with one node as root
    jsonString = $"{{ \"rootNode\": {{{jsonString.Trim().TrimStart('{').TrimEnd('}')}}} }}";
    //// Now it is secure that we have always a Json with one node as root 
    var xd = JsonConvert.DeserializeXmlNode(jsonString);

    //// DataSet is able to read from XML and return a proper DataSet
    var result = new DataSet();
    result.ReadXml(new XmlNodeReader(xd), mode);
    return result;
}

E.g. If you want to infer a strongly typed schema from the data:

var dataset = ReadDataFromJson(yourString, XmlReadMode.InferTypedSchema);
shA.t
  • 16,580
  • 5
  • 54
  • 111
  • The problem with this is the xml format won't retain int, bool etc. If you use this method and convert it back to a json string then all your booleans will now be "false" (with quotes) instead of just false (without quotes) and your ints will be "1" instead of 1. – nickvans Aug 03 '18 at 14:14
  • @nickvans I update my answer to support XML read options that can infer types -HTH ;). – shA.t Aug 04 '18 at 04:20
1
Private Function convertJsonStringToDataSet(jsonString As String) As DataSet
    Dim xd As New XmlDocument()
    jsonString = "{ ""rootNode"": {" + jsonString.Trim().TrimStart("{"c).TrimEnd("}"c) + "} }"
    xd = DirectCast(Newtonsoft.Json.JsonConvert.DeserializeXmlNode(jsonString), XmlDocument
    Dim ds As New DataSet()
    ds.ReadXml(New XmlNodeReader(xd))
    Return ds
End Function
shA.t
  • 16,580
  • 5
  • 54
  • 111
0

I prefer you follow Nick's suggestion... and perhaps your web services should modified because I saw similar property on each Table and Table1 and property inside...

  1. Create class using json2csharp.com and I got this

    public class Table
    {
        public string DisplayVoucherNumber { get; set; }
        public string ActualDate { get; set; }
        public string AccountName { get; set; }
        public string NetWeight { get; set; }
        public string Weight { get; set; }
        public string Pcs { get; set; }
        public string Difference { get; set; }
    }
    
  2. Deserialize json string using
    List<Table> list = JsonConvert.DeserializeObject<List<Table>>(jsonstring);

  3. You can access that list object to put on your DataSet.
0
  1. Create a class for your deserialized data.

  2. Use:

    YourClass yourObject = JsonConvert.DeserializeObject<YourClass>(jsonStr);
    
shA.t
  • 16,580
  • 5
  • 54
  • 111
Maciej Jureczko
  • 1,560
  • 6
  • 19
  • 23
0

try this,

string json = @"{
  'Table1': [
    {
      'id': 0,
      'item': 'item 0'
    },
    {
      'id': 1,
      'item': 'item 1'
    }
  ]
}";

DataSet dataSet = JsonConvert.DeserializeObject<DataSet>(json);

DataTable dataTable = dataSet.Tables["Table1"];

Serialize json : Link

Boopathi.Indotnet
  • 1,280
  • 15
  • 18