簡體   English   中英

將Json List反序列化為C#List對象

[英]Deserialize Json List to C# List objects

我有返回json字符串的類,但我想將其反序列化為C#列表對象。 我當前的代碼如下所示

public class JsonBuilder
    {
        public static string BuildJson(DateTime fromDate, DateTime toDate)
        {
            var list = new List<dynamic>();

           // create list with json object from service

            var jsonObjList = JsonConvert.SerializeObject(list);
            var des = (List<JsonObject>)JsonConvert.DeserializeObject(jsonObjList, typeof(List<JsonObject>));

            return JsonConvert.SerializeObject(list);
        }

嘗試反序列化“序列化” json字符串時引發的異常

An exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll but was not handled in user code

Additional information: Error converting value 


InnerException:

{"Could not cast or convert from System.String to MvcWebApp.Models.JsonObject."}

您是否嘗試過:

var des = (List<DeserializeObjects>)JsonConvert.DeserializeObject(jsonObjList, jsonObjList.GetType()));

或這個:

var des = (List<DeserializeObjects>)JsonConvert.DeserializeObject(jsonObjList, typeof(List<dynamic>));

否則,這篇文章也可以幫助您實現目標:

使用Json.net將JSON對象反序列化為動態對象

嘗試這個

 var jsonObjList = JsonConvert.SerializeObject(list);
 dynamic resultList = JsonConvert.DeserializeObject(jsonObjList);

我會嘗試這class

public class Author
{
    public int id { get; set; }
    public string slug { get; set; }
    public string name { get; set; }
    public string first_name { get; set; }
    public string last_name { get; set; }
    public string nickname { get; set; }
    public string url { get; set; }
    public string description { get; set; }
}

public class CustomFields
{
    public List<string> tags { get; set; }
}

public class Post
{
    public int id { get; set; }
    public string type { get; set; }
    public string slug { get; set; }
    public string url { get; set; }
    public string status { get; set; }
    public string title { get; set; }
    public string title_plain { get; set; }
    public string content { get; set; }
    public string excerpt { get; set; }
    public string date { get; set; }
    public string modified { get; set; }
    public List<object> categories { get; set; }
    public List<object> tags { get; set; }
    public Author author { get; set; }
    public List<object> comments { get; set; }
    public List<object> attachments { get; set; }
    public int comment_count { get; set; }
    public string comment_status { get; set; }
    public CustomFields custom_fields { get; set; }
}

public class YourObject
{
    public string status { get; set; }
    public int count { get; set; }
    public int count_total { get; set; }
    public int pages { get; set; }
    public List<Post> posts { get; set; }
}

然后,您使用以下方法反序列化:

var yourObject = JsonConvert.DeserializeObject<YourObject>(json);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM