如何在C#上从json读取数据 [英] How to read data from json on C#

查看:943
本文介绍了如何在C#上从json读取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将以下json对象传递给c#服务器

I have the following json Object that I pass to my c# server

[
    {
        "ID": 1,
        "FirstName": "Jay",
        "LastName": "Smith"
    },
    {
        "ID": 2,
        "FirstName": "Rich",
        "LastName": "Son"
    },
    {
        "ID": 3,
        "FirstName": "Emmy",
        "LastName": "Wat"
    }
]

我创建了一个这样的类

public class Person
{
    public int ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

}

当我这样做

public static string addRecord(string details)
{
    Person tempRecord = JsonConvert.DeserializeObject<Person>(details);
    string tempFN = tempRecord.FirstName;
    return tempFN;
}

我无法获得实际结果.

我在做什么错了?我必须在Person类中再创建一个List吗?有帮助吗?

What am I doing Wrong? Do I have to make another List in my Person class? Any help?

更新-我的记录来自Grid,这就是我将其发送到服务器的方式

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) {
        }
    });

推荐答案

您的JSON包含三个Person的集合,但是您试图将JSON反序列化为单个Person.

Your JSON contains a collection of three Persons, but you're attempting to deserialize the JSON as though it were a single Person.

Person tempRecord = JsonConvert.DeserializeObject<Person>(details);

此行需要返回 s的 collection .

var tempRecords = JsonConvert.DeserializeObject<List<Person>>(details);

这篇关于如何在C#上从json读取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆