简体   繁体   中英

Deserializing dynamic JSON values into DataTable

I' have a chunky JSON object that I am trying to deserialize in my application.

I've used JsonC2Sharp.com which helped me to get the exact C# object structure of my JSON, however I'd like to make some modifications...

Currently my JSON looks like this:

 "Parts":[
           {
             "PartNum":1,
             "PartCount":15,
             "Table":[
                       {
                        "Col1":"Some Text",
                        "Col2":0
                       },
                       {
                        "Col1":"Some Text 2",
                        "Col2":1
                       }
                     ]
            }
          ]

And my C# object structure looks like this

public class Parts
{
     public int PartNum {get;set;}
     public int PartCount {get;set;}
     public List<Table> table {get;set;}
}

public class Table 
{
     public string Col1 {get;set;}
     public int Col2 {get;set;}
}

My dilemna is that the JSON Table array might contain different columns every time I call this endpoing. So another time I can get something like ( Table contains 3 key:values)

 "Parts":[
           {
             "PartNum":1,
             "PartCount":15,
             "Table":[
                       {
                        "Col1":"Some Text",
                        "Col2":0,
                        "Col3":"SOme other value"
                       },
                       {
                        "Col1":"Some Text 2",
                        "Col2":1,
                        "Col3":"Some other value 2",
                       }
                     ]
            }
          ]

Is there any way I can NOT specify the Col1, Col2 and Col3 in my object and instead dump all the columns and values into a C# DataTable ?

You can try this custom implementation.

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
...
public static class Tools
{
  public static JsonSerializerSettings jsonSettings = new JsonSerializerSettings {
    ObjectCreationHandling = ObjectCreationHandling.Replace,
    ReferenceLoopHandling = ReferenceLoopHandling.Ignore
  }; 

  public static string JSerialize<T>(T source) {       
    return JsonConvert.SerializeObject(source, Formatting.Indented, jsonSettings);
  }

  public static T JDeserialize<T>(string source) {       
    return JsonConvert.DeserializeObject<T>(source, jsonSettings);
  }
}
var json = @"{
  'PartNum': 1,
  'PartCount': 15,
  'Table': [
    {
      'Col1': 'Some Text',
      'Col2': 0
    },
    {
      'Col1': 'Some Text 2',
      'Col2': 1
    }
  ]
}";

// you can cast your custom class or list
var item = Tools.JDeserialize<object>(json);

Console.WriteLine(Tools.JSerialize(item));

/*
{
  "PartNum": 1,
  "PartCount": 15,
  "Table": [
    {
      "Col1": "Some Text",
      "Col2": 0
    },
    {
      "Col1": "Some Text 2",
      "Col2": 1
    }
  ]
}
*/

Another alternative:

var data = (JObject)JsonConvert.DeserializeObject(json);
var dt = Tools.JDeserialize<List<object>>(Tools.JSerialize(data["Table"]));

Console.WriteLine(Tools.JSerialize(dt));

this code was tested in Visual Studio. It will convert your json table part to DataTable

var jObject = JObject.Parse(json);
    
    var jArray = jObject["Parts"][0]["Table"];

    DataTable dt = new DataTable();

    foreach (JProperty jprop in jArray[0])
        dt.Columns.Add(new DataColumn(jprop.Name));

    foreach (var item in jArray)
    {
        var dr = dt.NewRow();
        foreach (JProperty jprop in item)
            dr[jprop.Name] = jprop.Value;

        dt.Rows.Add(dr);
    }

output

    Col1         Col2

    Some Text     0
    Some Text 2   1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM