Convert a data string to a JSON object

I have a datatable whis has only one row and looks like

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

The data columns are America, Africa, Japan.

Now I want to convert datatable to JSon so that json looks like

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

My attempt was

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

But that did not work.

Any help would be appreciated. Thanks!

+8
source share
4 answers

Json.NET DataTableConverter, . DataSet, DataRow. , DataRow DataRow, .

DataRow , DataTable, - JArray, JArray.FromObject(), , :

        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.

:

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

:

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.
    }
}
+12

? "SerializeObject":

string js = JsonConvert.SerializeObject(datatable);

. JSON.

+2

Gazzi, NewtonSoft.Json, Visual Studio.

, , , , ​​ Country.cs, .

[Serializable]
public class CountryModel {
   public int ID { get; set; }
   public string Title { get; set; }
   public List<ValueModel> Values { get; set; }
}

[Serializable]
public class ValueModel {
   public int ValueID { get; set; }
   public string Type { get; set; }
}

. / Newtonsoft.

+2

(ExtensionMethods):

public static string ToJson(this DataTable dt)
{
    List<Dictionary<string, object>> lst = new List<Dictionary<string, object>>();
    Dictionary<string, object> item;
    foreach (DataRow row in dt.Rows)
    {
            item = new Dictionary<string, object>();
                foreach (DataColumn col in dt.Columns)
                {
                    item.Add(col.ColumnName, (Convert.IsDBNull(row[col]) ? null : row[col]));       
        }
        lst.Add(item);
    }
        return Newtonsoft.Json.JsonConvert.SerializeObject(lst);
}

:

DataTable dt = new DataTable();
.
.
.
var json = dt.ToJson();
0

Source: https://habr.com/ru/post/1613546/


All Articles