Using json.net from string to datatable in C#

懵懂的女人 提交于 2019-12-12 03:59:30

问题


Hopefully can someone help me with an example, because I'm new in JSON: From a webservice I receive a JSON string. I understand it is created from a datatable. How do I manage in C# to Deserialize this to a dataset? Maybe someone has something for me.

{
  "DataToJohnson": {
    "0": {
      "maat_id": "1",
      "maat": "11"
    },
    "1": {
      "maat_id": "2",
      "maat": "11+"
    },
    "2": {
      "maat_id": "3",
      "maat": "12+"
    },
    "3": {
      "maat_id": "4",
      "maat": "12/13"
    }
  }
}

Thanks!

Raymond


回答1:


You could define a model that will represent this JSON data:

public class Data
{
    public int Maat_id { get; set; }
    public string Maat { get; set; }
}

public class MyModel
{
    public Dictionary<int, Data> DataToJohnson { get; set; }
}

and then use Json.NET to deserialize this string to the model

var json = 
@"{
  ""DataToJohnson"": {
    ""0"": {
      ""maat_id"": ""1"",
      ""maat"": ""11""
    },
    ""1"": {
      ""maat_id"": ""2"",
      ""maat"": ""11+""
    },
    ""2"": {
      ""maat_id"": ""3"",
      ""maat"": ""12+""
    },
    ""3"": {
      ""maat_id"": ""4"",
      ""maat"": ""12/13""
    }
  }
}";
MyModel model = JsonConvert.DeserializeObject<MyModel>(json);
foreach (var item in model.DataToJohnson)
{
    Console.WriteLine(
        "id: {0}, maat_id: {1}, maat: {2}", 
        item.Key, item.Value.Maat_id, item.Value.Maat
    );
}


来源:https://stackoverflow.com/questions/5035608/using-json-net-from-string-to-datatable-in-c-sharp

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