gpt4 book ai didi

c# - JSon反序列化哈希

转载 作者:行者123 更新时间:2023-11-30 15:30:46 26 4
gpt4 key购买 nike

在我的senario中,JSon响应实体中有一段代码如下:

"hashkeys":
{
"key1":"value1",
"key2":"value2",
"key3":"value3"
}

“key1”、“key2”、“key3”等键(甚至键的数量)仅在运行时已知,而无法在编码时确定。

我如何编写 JSon 实体以反序列化此类响应?我正在使用 C# 语言 DataContractJsonSerializer。

我的测试代码:

[DataContract]
class Test {
[DataMember(Name = "hashkeys")]
public Dictionary<string, string> dic { get; set; }

}

class Program
{
public static T FromJson<T>(string strJson) where T : class
{
DataContractJsonSerializer ds = new DataContractJsonSerializer(typeof(T));
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(strJson)))
{
return ds.ReadObject(ms) as T;
}
}

static void Main(string[] args)
{
string json = @"{""hashkeys"":{""key1"":""value1"",""key2"":""value2""}}";
Test MyResponse = FromJson<Test>(json);
Console.WriteLine(MyResponse);
}
}

最佳答案

你可以使用

像这样制作字符串字符串字典

string json = @"{""key1"":""value1"",""key2"":""value2""}";   
Dictonary<string,string> MyResponse = JsonConvert.DesirializeObject<Dictionary<string,string>>(json);
Console.WriteLine(values.Count);
// 2
Console.WriteLine(values["key1"]);
// Value1

更多示例和引用Click Here

关于c# - JSon反序列化哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21669473/

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