将JSON转换为Datatable

oalqel3c  于 2023-05-02  发布在  其他
关注(0)|答案(1)|浏览(117)

在尝试将下面的json转换为DataTable时,我得到了这个错误:

**错误:**Newtonsoft。Json.JsonSerializationException:'阅读DataTable时意外的JSON标记。应为StartArray,但获得了StartObject。路径“”,行% 1,位置% 1。”

var prettyJson = "{
  "AAPL": {
    "390": [
      {
        "root": "AAPL",
        "expiry": "2024-06-21T00:00:00",
      }
    ]
  }
}"

var dt = JsonConvert.DeserializeObject<DataTable>(prettyJson);
6rqinv9w

6rqinv9w1#

你必须使你的json对象变平

DataTable dt = JsonConvert.DeserializeObject<DataTable>(prettyJson, new ToDataTableConverter());

public class ToDataTableConverter : JsonConverter<DataTable>
{
    public override DataTable ReadJson(JsonReader reader, Type objectType, DataTable existingValue, bool hasExistingValue, JsonSerializer serializer)
    {
        var rows = new JArray(JObject.Load(reader).Properties()
                       .SelectMany(x => GetRows(x.Values())));

        return rows.ToObject<DataTable>();
    }

    private JArray GetRows(IEnumerable<JToken> val)
    {
        var list = new List<JObject>();
        foreach (JProperty jo in val)
        {
            var key = jo.Name;
            foreach (JObject o in jo.Value)
            {
                o.AddFirst(new JProperty("key", key));
                list.Add(o);
            }
        }
        return new JArray(list);
    }

    public override void WriteJson(JsonWriter writer, DataTable value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
    public override bool CanWrite
    {
        get { return false; }
    }
}

输出

[{"key":"390","root":"AAPL","expiry":"2024-06-21T00:00:00"}]

相关问题