2017-02-24 75 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 - **它已经工作**。 –