gpt4 book ai didi

c# - 访问 JSON 字符串中的无效成员名称

转载 作者:太空宇宙 更新时间:2023-11-03 23:24:29 26 4
gpt4 key购买 nike

我有这个字符串

"{\"0\":\"test\"}"

我正在使用 JSON.net .我试过这条线

var j = JsonConvert.DeserializeObject(input_string)
var t = j["0"]; //This causes a compile error
var k = j.Keys

我也许可以更改我的输入字符串,但我宁愿保持这种方式。我如何在 json.net 中访问它?

最佳答案

目前,您正在使用非泛型 DeserializeObject,它会返回一个 object,因此会出现编译时错误。一种可能是将 json 解析为 JObject:

void Main()
{
var json = "{\"0\":\"test\"}";
var jobject = JObject.Parse(json);
Console.WriteLine(jobject["0"]);
}

另一种是创建一个类并使用适当的 JsonProperty 属性对其进行注释:

void Main()
{
var json = "{\"0\":\"test\"}";
var obj = JsonConvert.DeserializeObject<X>(json);
Console.WriteLine(obj.Foo);
}

public class X
{
[JsonProperty("0")]
public string Foo { get; set; }
}

编辑

您可以使用 foreach 迭代该 JObject:

foreach (var element in jobject)
{
Console.WriteLine($"Key: {element.Key}, Value: {element.Value }");
}

或者使用 LINQ:

var enumerable = jobject.AsJEnumerable()
.Cast<JProperty>()
.Select(x => new { Key = x.Name, Value = x.Value });

关于c# - 访问 JSON 字符串中的无效成员名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34290675/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com