首页 > 解决方案 > C# 中的 JSON 解析 - 将字符串数组提取到另一个数组

问题描述

我有一个从 API 返回的 JSON 字符串,它有 1 个字段 - ApiErrorMessage 和一个数组 - BlogCategoryList

entry = "{\"ApiErrorMessage\":null,\"BlogCategoryList\": 
[{\"BlogCategoryId\":2,\"BlogCategoryDescr\":\"To Start\"}, 
{\"BlogCategoryId\":1,\"BlogCategoryDescr\":\"Introduction\"}, 
{\"BlogCategoryId\":1,\"BlogCategoryDescr\":\"Introduction\"}]}"

需要将该 JSON 字符串数组提取到一个仅具有该 JSON 字符串数组的变量中(它应该如下所示)。因为我需要将它传递给反序列化。

{"BlogCategoryList":
   [{"BlogCategoryId":2,"BlogCategoryDescr":"To Start"}, 
   {"BlogCategoryId":1,"BlogCategoryDescr":"Introduction"}, 
   {"BlogCategoryId":1,"BlogCategoryDescr":"Introduction"}]
}

public class BlogCategoryResult
{
    public BlogCategoryResult()
    {
        this.BlogCategoryList = new List<BlogCategory>();
    }

    public string ApiErrorMessage { get; set; }        
    public List<BlogCategory> BlogCategoryList { get; set; }
}

我的代码。只是不知道如何提取它。

   // Note: entry is a string type.
   var entry = result.Content.ReadAsStringAsync().Result;

   // I tried this, but the result is not correct.
   string[] resultArray = entry.Split('[');

   // I tried this, I get the list but then I get 'Can not convert Array to String' on the last command where I do the cast.
   JObject o = JObject.Parse(entry);
   string name = (string)o["ApiErrorMessage"];                        
   JArray list = (JArray)o["BlogCategoryList"];
   string listofentries = (string)list;

   // Deserializing the response (just the list) received from web api and storing into a model.  
   blogCategoryResult.BlogCategoryList = JsonConvert.DeserializeObject<List<BlogCategory>>
   (listofentries);

标签: jsonasp.net-mvc

解决方案


我认为您应该通过在 and 之间传递类以及 and 中的整个变量来反序列化整个json BlogCategoryResult,之后您可以轻松选择属性<>JsonConvert.DeserializeObjectentry()BlogCategoryList

var entry = result.Content.ReadAsStringAsync().Result;
blogCategoryResult.BlogCategoryList = JsonConvert
    .DeserializeObject<BlogCategoryResult>(entry)
    .BlogCategoryList;

推荐阅读