如何从C#上的json读取数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17351037/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to read data from json on C#
提问by EagleFox
I have the following json Object that I pass to my c# server
我有以下 json 对象,我将其传递给我的 c# 服务器
[
{
"ID": 1,
"FirstName": "Jay",
"LastName": "Smith"
},
{
"ID": 2,
"FirstName": "Rich",
"LastName": "Son"
},
{
"ID": 3,
"FirstName": "Emmy",
"LastName": "Wat"
}
]
I create a Class like this
我创建了一个这样的类
public class Person
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
When I do this
当我这样做时
public static string addRecord(string details)
{
Person tempRecord = JsonConvert.DeserializeObject<Person>(details);
string tempFN = tempRecord.FirstName;
return tempFN;
}
I can't get the actual result.
我无法得到实际结果。
What am I doing Wrong? Do I have to make another List in my Person class? Any help?
我究竟做错了什么?我是否必须在我的 Person 类中制作另一个列表?有什么帮助吗?
UPDATE - my record is from Grid and this is how I send it to my server
更新 - 我的记录来自网格,这就是我将它发送到我的服务器的方式
var jsonD = Ext.encode(Ext.pluck(this.myGridStore.data.items, 'data'));
Ext.Ajax.request({
scope: this,
method: 'POST',
url: 'myApp/AddRecord',
headers: { 'Content-Type': 'application/json' },
dataType: 'json',
jsonData: jsonD,
success: function (response) {
},
failure: function (response) {
}
});
采纳答案by Amy
Your JSON contains a collection of three Persons, but you're attempting to deserialize the JSON as though it were a single Person.
您的 JSON 包含三个Persons的集合,但您试图反序列化 JSON,就好像它是单个Person.
Person tempRecord = JsonConvert.DeserializeObject<Person>(details);
This line needs to return a collectionof Persons.
这条线需要返回一个集合的Person秒。
var tempRecords = JsonConvert.DeserializeObject<List<Person>>(details);

