我无法反序列化json数组

时间:2018-03-07 09:38:41

标签: c# json

我输入了json

{
    "StudentData": {
        "Students": [{
            "StudentId": 76769,
            "StudentName": "*****",
            "Contacts": [{
                "ContactName": "****",
                "ContactEmail": "****",
                "АvailableContactEmail": true,
                "ContactMobile": "****",
                "АvailableContactMobile": true
            }]
        }]
    }
}

和此代码

public class Contacts
{
    public string ContactName { get; set; }
    public string ContactEmail { get; set; }
    public bool АvailableContactEmail { get; set; }
    public string ContactMobile { get; set; }
    public bool АvailableContactMobile { get; set; }
}

public class Students
{
    public int StudentId { get; set; }
    public string StudentName { get; set; }
    public List<Contacts> Contacts { get; set; }
}

public class StudentData
{
    public List<Students> Students { get; set; }
}

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
    log.Info("C# HTTP trigger function processed a request.");

       // Get request body
        dynamic data = await req.Content.ReadAsAsync<object>();
        var stuData = JsonConvert.DeserializeObject <StudentData>(data?.StudentData.ToString());

        RootObjectNew RootObjectNewObject = new RootObjectNew();
        List<StudentNew> students = new List<StudentNew>();

        foreach (var stu in stuData.Students)
        {
            var stuContacts = JsonConvert.DeserializeObject <List<Contacts>>(stu?.Contacts.ToString());
        }
}

但我无法联系。得到错误

  

解析值时遇到意外的字符:S。路径&#39;&#39;,行   0,位置0。

请帮助对结构进行正确的分析。 我查看了许多类似的主题,但他们没有帮助我

2 个答案:

答案 0 :(得分:2)

data?.StudentData.ToString()不会为您提供JSON对象的表示,只会显示它的名称。

尝试以下

public class StudentDataContainer 
{
    public StudentData StudentData { get; set; }

}

var data = await req.Content.ReadAsAsync<StudentDataContainer>();

答案 1 :(得分:0)

我会建议这些课程

    public class Contact
    {
        public string ContactName { get; set; }
        public string ContactEmail { get; set; }
        public bool АvailableContactEmail { get; set; }
        public string ContactMobile { get; set; }
        public bool АvailableContactMobile { get; set; }
    }

    public class Student
    {
        public int StudentId { get; set; }
        public string StudentName { get; set; }
        public List<Contact> Contacts { get; set; }
    }

    public class StudentData
    {
        public List<Student> Students { get; set; }
    }

    public class RootObject
    {
        public StudentData StudentData { get; set; }
    }

然后你就可以做到这一点

     RootObject root = JsonConvert.DeserializeObject<RootObject>(json);