c#Newtonsoft反序列化所有对象列表中的json字符串

本文关键字:json 字符串 列表 对象 反序列化 c#Newtonsoft | 更新日期: 2023-09-27 17:58:52

我有以下类

using System;
public class AppEventsClass
{
    public string title { get; set; }
    public string description { get; set; }
}

调用远程Web服务后,我检索以下json字符串:

{"d":"[title'":'"test'",'"description'":'"test desc'"},{'"title'":'"test2'",'"description'":'"desc test 2'"}]"}

在检索到json字符串后,我如何转换List<>中的字符串的AppEventsClass?

我尝试了几种解决方案,但都不适合我。例如:

List<AppEventsClass> result = new List<AppEventsClass>();
result = JsonConvert.DeserializeObject<List<AppEventsClass>>(content).ToList();

这是序列化字符串的.asmx:

[ScriptMethod(UseHttpGet = true)]
    public string GetEvents()
    {
        using (mySQLDataContext ctx = new secondosensoSQLDataContext())
        {
            List<eventi> eventiList = ctx.eventi.ToList();
            List<AppEventsClass> eventiClassList = new List<AppEventsClass>();
            for (int i = 0; i < eventiList.Count; i++)
            {
                AppEventsClass a = new AppEventsClass();
                a.title = eventiList[i].titlolo_evento;
                a.description = eventiList[i].descrizione_evento;
                eventiClassList.Add(a);
            }
            var json = JsonConvert.SerializeObject(eventiClassList);
            return json;
        }
    }

c#Newtonsoft反序列化所有对象列表中的json字符串

第一个问题似乎是我们检索到的响应格式不正确假设json字符串如下所示:

 {"d":[{"title":"test","description":"test desc"},{"title":"test2","description":"desc test 2"}]}

反序列化的正确类应该像以下

public class Rootobject
{
    public D[] d { get; set; }
}
public class D
{
    public string title { get; set; }
    public string description { get; set; }
}

感谢

PS。下面是一个工作示例:

class Program
{
    static void Main(string[] args)
    {
        string json = "{'"d'":[{title:'"test'",description:'"test desc'"},{title:'"test2'",description:'"desc test 2'"}]}";
        var result = Newtonsoft.Json.JsonConvert.DeserializeObject<Rootobject>(json);
    }
}
public class Rootobject
{
    public D[] d { get; set; }
}
public class D
{
    public string title { get; set; }
    public string description { get; set; }
}