简体   繁体   中英

Deserialize javascript associative array into C# Dictionary with Json.Net

I used JSON.stringify() to store a javascript associative array of integer keys with boolean values in a cookie eg var arr = {}; arr[9000001] = True; var arr = {}; arr[9000001] = True; . I can see the value of the string on the server in the following format: %7B%229000001%22%3Atrue%2C%229000003%22%3Atrue%2C%229000006%22%3Atrue%2C%229000009%22%3Atrue%7D where the first number is 9000001, second is 9000003, and so on.

I would like to use Json.Net to deserialize into a Dictionary<long,bool> or similar. I try the following

var result = JsonConvert.DeserializeObject<Dictionary<string, string>>(cookieValue);

but get the following exception

{"Unexpected character encountered while parsing value: %. Path '', line 0, position 0."}

I'm guessing deserialization is not possible in this scenario?

Frits van Campen found the missing piece. I wrote the following extension method that makes it easy to retrieve cookie values in C#. Set both urlDecode and fromJson to true and the object will be successfully deserialized.

/// <summary>
/// retrieve object from cookie
/// </summary>
/// <typeparam name="T">type of object</typeparam>
/// <param name="controller"></param>
/// <param name="cookieName">name of cookie</param>
/// <param name="urlDecode">true to enable url decoding of the string</param>
/// <param name="fromJson">true if the string in cookie is Json stringified</param>
/// <returns>object in the cookie, or default value of T if object does not exist</returns>
public static T GetFromCookie<T>(this Controller controller, string cookieName, 
                                 bool urlDecode = true, bool fromJson = false)
{
    var cookie = controller.HttpContext.Request.Cookies[cookieName];
    if (cookie == null) return default(T);
    var value = cookie.Value;

    if (urlDecode)
        value = Uri.UnescapeDataString(value);

    T result;
    if (fromJson)
        result = JsonConvert.DeserializeObject<T>(value);
    else
        result = (T)Convert.ChangeType(value, typeof(T));

    return result;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM