简体   繁体   English

使用Json.Net将javascript关联数组反序列化为C#字典

[英]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; 我使用JSON.stringify()将带有布尔值的整数键的javascript关联数组存储在cookie中,例如var arr = {}; arr[9000001] = True; JSON.stringify() 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. 我可以在服务器上以以下格式查看字符串的值: %7B%229000001%22%3Atrue%2C%229000003%22%3Atrue%2C%229000006%22%3Atrue%2C%229000009%22%3Atrue%7D其中第一个数字是9000001,第二个数字是9000003,依此类推。

I would like to use Json.Net to deserialize into a Dictionary<long,bool> or similar. 我想使用Json.Net反序列化为Dictionary<long,bool>或类似的Dictionary<long,bool> 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. 弗里斯·范·坎彭(Frits van Campen)找到了失踪的一块。 I wrote the following extension method that makes it easy to retrieve cookie values in C#. 我编写了以下扩展方法,使在C#中检索cookie值变得容易。 Set both urlDecode and fromJson to true and the object will be successfully deserialized. urlDecodefromJson都设置为true ,该对象将成功反序列化。

/// <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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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