从JSON文件创建Cookie:值类型影响及C#代码错误修复咨询
首先来梳理下你遇到的问题,然后一步步解决:
我将Cookie导出为JSON文件,内容如下:
[ { "name": "abc", "value": "0000", "domain": ".domain.com", "hostOnly": false, "path": "/", "secure": false, "httpOnly": false, "sameSite": "no_restriction", "session": false, "firstPartyDomain": "", "partitionKey": null, "expirationDate": 1734526188, "storeId": null }, { "name": "dfg", "value": "777", "domain": ".domain.it", "hostOnly": false, "path": "/", "secure": true, "httpOnly": true, "sameSite": "no_restriction", "session": false, "firstPartyDomain": "", "partitionKey": null, "expirationDate": 1684947948, "storeId": null } ]可以看到,部分值为字符串类型(如name),hostOnly为布尔类型,partitionKey为可空类型,expirationDate为整数类型。我使用的C#代码如下:
json = File.ReadAllText("json.txt"); JArray array = JArray.Parse(json); foreach(JObject cookie_json in array) { foreach(var entry in cookie_json) { cookies.Add(new Cookie(entry.Key, (string?)entry.Value)); } }但我遇到了两个问题:一是Cookie构造函数仅接受string类型作为Value参数,无法处理整数、布尔值及可空类型,可空类型会抛出异常;二是我错误地为JSON中的每个键值对创建了一个Cookie,而非为每个代表单个Cookie的JSON对象创建一个Cookie。请问该如何修复这些问题?
先解决第二个问题:错误创建Cookie的逻辑
你之前的代码犯了一个逻辑错误:每个JSON对象对应一个真实的Cookie实例,而不是每个键值对都新建一个Cookie。你需要遍历数组里的每个JObject(每个都是一个完整的Cookie数据),然后从这个对象中提取属性来初始化一个Cookie,而不是循环对象内的键值对。
再解决第一个问题:类型转换和空值处理
System.Net.Cookie的构造函数要求value是字符串,而你的JSON里有布尔、整数、null等多种类型,直接强制转换会报错。我们需要做安全的类型转换,把非字符串类型转为字符串,同时处理null值避免异常。
完整修复后的代码
using Newtonsoft.Json.Linq; using System.Net; using System.IO; using System.Collections.Generic; // 读取JSON文件内容 string jsonContent = File.ReadAllText("json.txt"); JArray cookieJsonArray = JArray.Parse(jsonContent); List<Cookie> cookieList = new List<Cookie>(); foreach (JObject cookieJsonObj in cookieJsonArray) { // 安全提取name和value,null的话用空字符串兜底 string cookieName = cookieJsonObj["name"]?.ToString() ?? string.Empty; string cookieValue = cookieJsonObj["value"]?.ToString() ?? string.Empty; // 创建Cookie核心实例(name和value是必填项) Cookie currentCookie = new Cookie(cookieName, cookieValue); // 逐个设置其他Cookie属性,处理不同类型和空值 // 设置Domain if (cookieJsonObj["domain"] != null) currentCookie.Domain = cookieJsonObj["domain"].ToString(); // 设置Path if (cookieJsonObj["path"] != null) currentCookie.Path = cookieJsonObj["path"].ToString(); // 处理布尔类型的Secure属性 if (cookieJsonObj["secure"] != null && bool.TryParse(cookieJsonObj["secure"].ToString(), out bool isSecure)) currentCookie.Secure = isSecure; // 处理布尔类型的HttpOnly属性 if (cookieJsonObj["httpOnly"] != null && bool.TryParse(cookieJsonObj["httpOnly"].ToString(), out bool isHttpOnly)) currentCookie.HttpOnly = isHttpOnly; // 处理整数类型的过期时间(Unix时间戳转DateTime) if (cookieJsonObj["expirationDate"] != null && long.TryParse(cookieJsonObj["expirationDate"].ToString(), out long unixExpTime)) currentCookie.Expires = DateTimeOffset.FromUnixTimeSeconds(unixExpTime).DateTime; // 其他可选属性(比如sameSite):.NET Framework的Cookie类没有直接的SameSite属性, // 如果是.NET Core/.NET 5+,可以用Cookie.SameSite属性,同样安全转换即可 // if (cookieJsonObj["sameSite"] != null) // currentCookie.SameSite = Enum.Parse<SameSiteMode>(cookieJsonObj["sameSite"].ToString()); // 把配置好的Cookie加入列表 cookieList.Add(currentCookie); }
关键细节说明
- 逻辑修正:外层循环处理每个Cookie对象,内层不再循环键值对,而是直接提取每个属性赋值给单个Cookie实例。
- 安全类型转换:
- 用
?.ToString()处理可能为null的属性,避免空引用异常; - 布尔和整数类型用
TryParse方法,确保转换失败时不会抛出异常,而是跳过赋值; - Unix时间戳格式的
expirationDate通过DateTimeOffset.FromUnixTimeSeconds转为.NET的DateTime类型,符合Cookie类的要求。
- 用
- 空值处理:对于
partitionKey、storeId这类Cookie类没有对应属性的字段,直接忽略即可;如果有需要处理的扩展属性,同样用安全转换的方式处理。
内容的提问来源于stack exchange,提问作者Alessandro
相关产品推荐
相关产品推荐

