UWP C#项目中Newtonsoft.Json引发StackOverflowException求助
UWP C#项目StackOverflowException排查求助
问题说明
将项目JSON序列化方式从System.Text.Json替换为Newtonsoft.Json后,应用可正常运行,但调试会话会被StackOverflowException中断(VS捕获异常,应用未崩溃)。
- 应用启动后调用
.Save()方法无异常,仅在上传图片后点击触发ContinueBtn_Click的按钮时出现问题 - 已反复排查代码,未发现明显无限循环逻辑,通过断点和日志确认
.Save()与ContinueBtn_Click方法本身仅执行一次

相关代码
UserData类(含Save方法)
public class UserData { public List<CMSession> userSessions { get; set;} public DatabaseConnection lastDatabaseConnection { get; set;} [JsonIgnore] JsonSerializerSettings serializerDefaults = new JsonSerializerSettings { Formatting = Formatting.Indented, //PreserveReferencesHandling = PreserveReferencesHandling.All, //ReferenceLoopHandling = ReferenceLoopHandling.Serialize, }; public UserData() { userSessions = new List<CMSession>(); } /// <summary> /// Saves the UserData to a serialized user.json file. /// </summary> /// <param name="devBreak">If debugging, may provide optional True value to break the debugger prior to save, allowing data manipulation.</param> public async Task Save(bool devBreak = false) { if (devBreak) { Debug.WriteLine("Saving with Break Mode. You may manipulate UserData in Immediate Window now, otherwise Continue."); Debug.Write(""); } try { StorageFile udFile = await ApplicationData.Current.LocalFolder.GetFileAsync(@"UserData\user.json"); var udData = JsonConvert.SerializeObject(this, serializerDefaults); await Windows.Storage.FileIO.WriteTextAsync(udFile, udData); Debug.WriteLine("User data was manually saved."); } catch(Exception ex) { if (App.cmDebugger.debug) { Debug.WriteLine("Failed to serialize user data to file: " + ex.Message); } } } }
调用.Save()的ContinueBtn_Click方法
// Clicked after user drops some files into a box, the files are processed then added to pendingInit (a List<WorkingImage>) private async void IUInit_ContinueBtn_Click(object sender, RoutedEventArgs e) { if (pendingInit.Count > 0) { for (int i = 0; i < pendingInit.Count; i++) { try { App.cmSession.IUSession.workAreaImages.Add(pendingInit[i]); } catch (Exception ex) { if (App.cmDebugger.debug) { Debug.WriteLine("Failed to move pending file to work area: " + ex.Message); try { Debug.WriteLine("Image: " + pendingInit[i].fileName); } catch { } } } } IUState = DataState.RefreshNeeded; App.cmSession.IUSession.sessionActive = true; // This appears to be where the exception occurs. await App.cmData.Save(); await InitializeIU(); } else { Init_Grid.Visibility = Visibility.Collapsed; } IUState = DataState.RefreshNeeded; }
应用启动后正常生成的JSON示例
{ "userSessions": [ { "LinkedSite": { "hasContentAccess": true, "hasMediaAccess": true, "lastResponse": " (some JSON in here)", "friendlyName": "website", "URL": "http://www.google.com/", "username": "usr", "status": "connected", "statusDetail": "Connected to the site without errors.", "lastConnectionTime": "2023-05-10T15:49:24.0182548-05:00" }, "IUSession": { "sessionActive": false, "workAreaImages": [] } } ], "lastDatabaseConnection": null }
序列化涉及的关联数据结构
CMSession
public class CMSession { public SiteConnection LinkedSite { get; set; } public ImageUploaderData IUSession { get; set; } public CMSession(SiteConnection linkedSite) { LinkedSite = new SiteConnection(linkedSite); IUSession = new ImageUploaderData(); } }
DatabaseConnection
public class DatabaseConnection { public string dbName = database; public string dbstate; public MySqlConnection connection; }
SiteConnection
public class SiteConnection { public string friendlyName { get; set; } public string URL { get; set; } public string username { get; set; } public string status { get; set; } public string statusDetail { get; set; } public DateTime lastConnectionTime { get; set; } public bool hasContentAccess; public bool hasMediaAccess; public object lastResponse; }
ImageUploaderData
public class ImageUploaderData { public bool sessionActive { get; set; } = false; public List<WorkingImage> workAreaImages { get; set; } = new List<WorkingImage>(); }
内容的提问来源于stack exchange,提问作者Mark L
相关产品推荐
相关产品推荐

