2017-02-24 68 views
0

我有對應於該C#類Deserialise並提取陣列數據表

public class MyClass 
{ 
    public string firstString {get; set;} 
    public string secondString {get; set;} 
    public List<Person> person{get; set;} 
} 

public class Person 
{ 
    public string age {get; set;} 
    public string fullName {get; set;} 
} 

線與錯誤JSON字符串:

List<MyClass> myClassList = JsonConvert.DeserializeObject<List<MyClass>>(JsonString); 

目標:目標是從對應於類MyClass的JSON字符串中將Person細節獲取到dataTable中。

如果反序列化已經工作,計劃讓Linq選擇Person並將其放入dataTable中。

而deserialising的JSON字符串MyClass的我得到這個錯誤:

Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'System.Collections.Generic.List`1[Project.MyClass]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.\r\nTo fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.\r\nPath 'firstString', line 1, position 16."}

+0

感謝編輯@Caesay –

回答

1

異常消息是自我解釋。您正在向客戶端傳遞一個對象,並期望將其解析爲一個錯誤的集合,因此要麼更改JSON字符串以發送MyClass的數組,或者只傳遞一個對象,然後像這樣解析它: -

MyClass myClassObj = JsonConvert.DeserializeObject<MyClass>(JasonString); 

如果您JSON對象應該是這個樣子: -

var jsonObj = { 
    "firstString" : "foo", 
    "secondString" : "bar", 
    "person": [ { "age" : 12, "fullName" : "foo1" }, 
       { "age" : 10, "fullName" : "foo2" } ] 
}; 
+0

感謝勞爾。我用JsonConvert.DeserializeObject (JasonString) –

+0

謝謝勞爾。我使用'JsonConvert.DeserializeObject (JasonString)'as adviced,但myClassObj具有** NULL ** values.What可能是問題? –

+0

謝謝@Rahul - **它已經工作**。 –