Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSon deserialize for hash

In my senario, there is a piece of code like below in the JSon response entity:

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

The keys like "key1","key2","key3", (and even the number of the keys), are only known at runtime, but cannot be determined at coding time.

How can I code the JSon entity to deserialize such kind of response? I am using C# language DataContractJsonSerializer.

My testing code:

[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);
    }
}
like image 981
Weiquan Zhang Avatar asked Jun 27 '26 18:06

Weiquan Zhang


2 Answers

you can use

Make a Dictionary of string and string like this

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

For more examples and references Click Here

like image 119
Kaushik Avatar answered Jun 30 '26 07:06

Kaushik


Deserialize it to Dictionary<string, string>.

It's a collection of KeyValuePair<string, string>, which is exactly what you're trying to deal with. "KeyX" will become Key and "valueX" will be the Value for dictionary entiry.

like image 37
MarcinJuraszek Avatar answered Jun 30 '26 07:06

MarcinJuraszek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!