c#Newtonsoft在对象列表中反序列化一个json字符串

时间:2016-07-27 19:04:49

标签: c# json web-services serialization deserialization

我有以下课程

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<>中转换字符串?与Newtonsoft合作的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;
        }

    }

1 个答案:

答案 0 :(得分:0)

第一个问题似乎是我们检索到的响应没有正确形成 假设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; }
}