c# – 将数据行转换为JSON对象

前端之家收集整理的这篇文章主要介绍了c# – 将数据行转换为JSON对象前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个数据表whis只有一行,看起来像
America              |  Africa               |     Japan     |   
   -------------------------------------------------------------
  {"Id":1,"Title":"Ka"} | {"Id":2,"Title":"Sf"} | {"Id":3,"Title":"Ja","Values":{"ValID":4,"Type":"Okinawa"}}

数据列是美国,非洲,日本

现在我想将数据表转换为JSon,使json看起来像

{
"America": {
    "Id": 1,"Title": "Ka"
},"Africa": {
    "Id": 2,"Title": "Sf"
},"Japan": {
    "Id": 3,"Title": "Ja","Values": {
        "ValID": 4,"Type": "Okinawa"
    }
   }
  }

我的尝试是,

string js = JSonConvverter.Serializeobject(datatable);
    var objType =  JObject.Parse(js);

但它没有用.

任何帮助将不胜感激.谢谢!

解决方法

Json.NET有一个特殊的内置转换器 DataTableConverter,它以缩写格式输出数据表.虽然它也有 one for DataSet,但它没有 DataRow的特定内置转换器.因此,在序列化DataRow时,它将序列化DataRow的所有字段和属性,从而产生更详细的输出.

如果要以DataTable使用的更紧凑的形式序列化DataRow,最简单的方法是使用JArray.FromObject()将整个表序列化为JArray,然后选择第一个元素,如下所示:

var datatable = MakeTable();

        var objType = JArray.FromObject(datatable,JsonSerializer.CreateDefault(new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore })).FirstOrDefault(); // Get the first row            
        var js = objType.ToString(); 

        Debug.WriteLine(js); // Outputs abbreviated JSON as desired.

哪个输出

06001

完整示例:

public class Values
{
    public int ValID { get; set; }
    public string Type { get; set; }
}

public class Place
{
    public int Id { get; set; }
    public string Title { get; set; }
    public Values Values { get; set; }
}

public class TestClass
{
    static DataTable MakeTable()
    {
        var table = new DataTable();

        table.Columns.Add("America",typeof(Place));
        table.Columns.Add("Africa",typeof(Place));
        table.Columns.Add("Japan",typeof(Place));

        DataRow row = table.NewRow();

        row["America"] = JsonConvert.DeserializeObject<Place>(@"{""Id"":1,""Title"":""Ka""}");
        row["Africa"] = JsonConvert.DeserializeObject<Place>(@"{""Id"":2,""Title"":""Sf""}");
        row["Japan"] = JsonConvert.DeserializeObject<Place>(@"{""Id"":3,""Title"":""Ja"",""Values"":{""ValID"":4,""Type"":""Okinawa""}}");
        table.Rows.Add(row);    
        return table;

    }

    public static void Test()
    {
        var datatable = MakeTable();

        var objType = JArray.FromObject(datatable,JsonSerializer.CreateDefault(new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore })).FirstOrDefault(); // Get the first row            
        var js = objType.ToString(); 

        Debug.WriteLine(js); // Outputs abbreviated JSON as desired.
    }
}
原文链接:https://www.f2er.com/csharp/97346.html

猜你在找的C#相关文章