json - 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);
解决方案
我认为您应该通过在 and 之间传递类以及 and 中的整个变量来反序列化整个json BlogCategoryResult
,之后您可以轻松选择属性<
>
JsonConvert.DeserializeObject
entry
(
)
BlogCategoryList
var entry = result.Content.ReadAsStringAsync().Result;
blogCategoryResult.BlogCategoryList = JsonConvert
.DeserializeObject<BlogCategoryResult>(entry)
.BlogCategoryList;
推荐阅读
- ios - 无法快速解析字典
- c# - Xamarin:显示存储在本地 IIS 服务器上的图像
- python - 在 Python 中绘制多项式回归
- html - css grid object-fit:覆盖在Firefox中不起作用?
- python - 在 Azure Function App 上的 Flask 中从 POST 请求传递 JSON 数据
- selenium - 大家好,我想在扩展报告和失败测试用例的屏幕截图中为我通过的测试用例实现日志
- office-js - 如何诊断和修复 Office JS API 的性能问题
- java - 回收站视图隐藏且仅在单击下方的 EditText 时可见
- telegram - 通过 id 获取电报频道用户名
- python - 错误:psycopg2 的构建轮失败