在LogPersonDetails
中,我一直得到一个错误:
Error ArgumentException:无法将System.String转换为Card.Printer.CardHolder,不确定原因。
它传递的值是这样的:
{"FirstName":"ad","LastName":"asd","Email":"asd","CardNumber":"asd"}
我的理论是,它是这样做了两次,但当检查它,我得到:
$exception {“将值“{“FirstName”:“ad”,“LastName”:“asd”,“Email”:“asd”,“CardNumber”:“asd”}”转换为类型“Kiosk.Card.Printer. CardHolder”时出错。Path '',line 1,position 86."} Newtonsoft.Json.JsonSerializationException
这是Chromium WebView 2 Control和.NET到JavaScript的互操作。
有什么想法?
using Newtonsoft.Json;
using System;
using System.Windows;
using WebView2.DevTools.Dom;
namespace Kiosk.Card.Printer
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : System.Windows.Window
{
public MainWindow()
{
InitializeComponent();
Loaded += OnWindowLoaded;
}
private async void OnWindowLoaded(object sender, RoutedEventArgs e)
{
await webView.EnsureCoreWebView2Async();
webView.CoreWebView2.DOMContentLoaded += async (s, e) =>
{
var devToolsContext = await webView.CoreWebView2.CreateDevToolsContextAsync();
await devToolsContext.ExposeFunctionAsync("submitData", () =>
{
_ = webView.CoreWebView2.ExecuteScriptAsync($"window.getFormData()").ContinueWith(task =>
{
if (task.Exception == null)
{
string dataJson = task.Result;
if (dataJson != null)
{
LogPersonDetails(dataJson);
}
else
{
throw new InvalidOperationException("Result of getFormData() is empty.");
}
}
else
{
throw task.Exception;
}
});
});
};
webView.NavigateToString(@"
<h1>WebView2 Concept</h1>
<input type='text' id='firstName' placeholder='First Name'>
<input type='text' id='lastName' placeholder='Last Name'>
<input type='text' id='email' placeholder='Email'>
<input type='text' id='cardNumber' placeholder='Card Number'>
<button id='submitDataButton'>Submit Data</button>
<br/>
<b>Result:</b>
<div id='resultDisplay'></div>
<script>
function getFormData() {
var firstName = document.getElementById('firstName').value;
var lastName = document.getElementById('lastName').value;
var email = document.getElementById('email').value;
var cardNumber = document.getElementById('cardNumber').value;
var person = {
FirstName: firstName,
LastName: lastName,
Email: email,
CardNumber: cardNumber
};
return JSON.stringify(person);
}
document.getElementById('submitDataButton').addEventListener('click', function() {
submitData();
});
function submitData() {
console.log('submitData function called');
window.submitData();
}
</script>
");
}
#region Private Methods
private async void LogPersonDetails(string dataJson)
{
try
{
if (string.IsNullOrEmpty(dataJson))
{
throw new InvalidOperationException("Received empty data.");
}
var person = JsonConvert.DeserializeObject<CardHolder>(dataJson);
if (person != null)
{
string displayText = $"Received data: FirstName={person.FirstName}, LastName={person.LastName}, Email={person.Email}, CardNumber={person.CardNumber}";
await webView.Dispatcher.InvokeAsync(async () =>
{
await webView.CoreWebView2.ExecuteScriptAsync($"document.getElementById('resultDisplay').innerHTML = '{displayText}';");
});
}
else
{
throw new InvalidOperationException("Failed to deserialize data into CardHolder object.");
}
}
catch (Newtonsoft.Json.JsonSerializationException ex)
{
string errorMessage = $"Error during deserialization: {ex.Message}";
await webView.Dispatcher.InvokeAsync(async () =>
{
await webView.CoreWebView2.ExecuteScriptAsync($"document.getElementById('resultDisplay').innerHTML = '{errorMessage}';");
});
}
catch (System.InvalidCastException icex)
{
string errorMessage = $"Error during cast: {icex.Message}";
await webView.Dispatcher.InvokeAsync(async () =>
{
await webView.CoreWebView2.ExecuteScriptAsync($"document.getElementById('resultDisplay').innerHTML = '{errorMessage}';");
});
}
}
#endregion
}
public class CardHolder
{
public string? FirstName { get; set; }
public string? LastName { get; set; }
public string? Email { get; set; }
public string? CardNumber { get; set; }
}
}
1条答案
按热度按时间mwecs4sa1#
看起来JSON字符串是双重编码的。这意味着它已经被JSON编码了两次。搞定了