Newtonsoft.Json JsonConvert To Datatable

后端 未结 2 1351
栀梦
栀梦 2020-12-20 05:09

I have a code like this,

DataTable dt = new DataTable();

string data = \"{\\\"ProductId\\\":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,         


        
相关标签:
2条回答
  • 2020-12-20 05:30

    Your data cannot be converted to Datatabe

    When I try your code it gives me:

    Additional text found in JSON string after finishing deserializing object.

    However when I do:

    object obj  = JsonConvert.DeserializeObject(data); 
    

    works fine.

    You can also create your own class:

    public class MyObject
    {
        public int[] productId { get; set; }
        public string[] ProductName { get; set; }
    }
    
    MyObject obj = JsonConvert.DeserializeObject<MyObject>(data); 
    

    So for different types of data you have, you can create different classes:

        public class MyObject2{
        ...
        }
    
        public class MyObject3{
        ...
        }
        ...
    
    Object obj = null;
    try{
     obj = JsonConvert.DeserializeObject<MyObject>(data); 
    }catch{
          try{
          obj = JsonConvert.DeserializeObject<MyObject2>(data);
          }catch{
               try{
                 obj = JsonConvert.DeserializeObject<MyObject3>(data);
               }catch{
                 //Log error new type of data received
                 throw new Exception();
               }
          }
    
    }
    if (obj.GetType() == typeof(MyObject)){
       ...
    }else if (obj.GetType() == typeof(MyObject2)){
       ...
    }
    ....
    
    0 讨论(0)
  • 2020-12-20 05:41

    Your json must be an array of objects to be converted to a DataTable, it must start like this :

    "[{\"ProductId\..........
    

    end ends like this:

    ....,\"fieldName\":Value}]"
    
    0 讨论(0)
提交回复
热议问题