以我塞纳里奥,有一段代码像下面在JSON响应实体: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);
}
}
您的测试代码似乎工作,如果你改变JSON字符串这样'@ “{”“hashkeys”“:{”“key1”“:”“value1”“,”“key2”“:”“value2”“}}”' – Grundy
You are right。但是在反序列化之后,我所需要的字典没有任何价值。 –