c# - 从 JSON 字符串中反序列化选定的 JSON 对象

标签 c# json

我有一个类似于此的 JSON 字符串:

{
    "automatic" : "true",
    "brainstorm" : "1000",
    "zombies" : [{ "Name" : "Fred", "Grrh" : "50" }, { "Name" : "Sally", "Grrh" : "67" }, { "Name" : "Chris", "Grrh" : "23" }],
    "nightSkyRadius" : "30"
    ... could be anything here or at the same level as zombies ...
}

因此,在我的场景中,我知道数组中的 Zombie 对象将始终相同。但除此之外我什么都不知道。也就是说,与 zombies 相同的根可以有任意数量的值。值(value)。

所以我的问题是,如何使用 Json.NET 反序列化我的 zombies ?我不知道其他值是什么(如果值是正确的术语)所以我不能只创建一个对象来描述传入的 Json 字符串。所以我想我可以选择 zombies从 json 字符串中提取出来,然后反序列化它。

但是,我想,我必须编写一个字符串解析器来提取 zombies out.. 这似乎是一个额外的不必要步骤。不能Json.NET为我做这个?

另外,我试过 JsonConvert.DeserializeObject<dynamic>(responseString);但这只能处理在响应字符串中指定一个僵尸的情况。

谢谢,我希望zombies让这个问题看起来更酷哈哈

最佳答案

创建一个 Zombie 类并将 json 解析到其中。 Newtonsoft 足够聪明,可以为您解码

public class zombies
{
    public string Name;
    public int Grrh;
}

现在你可以做

var zombies = JsonConvert.DeserializeObject<List<zombies>>(responseString);

关于c# - 从 JSON 字符串中反序列化选定的 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45964395/

相关文章:

c# - 为什么 tempspace 结果在这里?

c# - MSTest 拒绝运行 64 位?

c# - 如何在同一页面上呈现两个菜单?

json - 将 json 文件导入到具有单个 json 列的 postgres 表中

java - Jersey 将空值序列化为 json : How to skip

java - 将数据从 fragment 发送到 Activity 并解析 json

c# - 在 C# 中为 'this' 创建一个实例变量

c# - 将 Expression<Func<T, V>> 转换为 Expression<Func<T, Nullable<V>>>

json - CloudFormation 存储桶策略 - 缺少必填字段 "Effect"

python - 操作系统错误: [Errno 57] Socket is not connected