我对Visual Studio很陌生。我正在编写一个程序,当输入员工姓名并单击“Get User”按钮时,该程序将从API中检索其签名(例如,如果输入员工姓名Jane Doe,则将从API字符串中检索签名“JNDO”)。
当使用文本框输入名称时,将成功读取所需信息。但是,当我将文本框替换为组合框以在用户键入时建议名称时,我会收到以下错误:
jsonReaderException:“解析值时遇到意外字符:<.路径'',行0,位置0.'此异常最初是在以下调用堆栈引发的:Webapi.cs Timesheets_Try_11.Controllers.Webapi.GetSignature(string)中的[External Code]Timesheets_Try_11.Form1.Button1_Click(object,System.EventArgs)中的Form1.cs[External Code]Timesheets_Try_11.Program.Main()中的Program.cs
通过使用断点来理解值,它声明
字符串不是JSON格式;
我的JSON字符串:
[{"signature":"JNDO","firstName":"Jane","fullName":"Doe, Jane","lastName":"Doe"}]
我的windows窗体的代码:
namespace TimeSheets_Try_11
{
public partial class Form1 : Form
{
WebAPI WA = new WebAPI();
public Form1()
{
InitializeComponent();
webBrowser1.Url = new Uri(StaticStrings.UrlIora);
}
private void label1_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
comboBox1.DataSource = WA.Getsignature(textBox2.Text);
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(AutoCompleteStringCollection combData)
{
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
this.Hide();
Form2 p = new Form2();
p.ShowDialog();
}
}
}
调用JSON的代码
namespace TimeSheets_Try_11.Controllers
{
class WebAPI
{
public string Getsignature(string name)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var cookies = FullWebBrowserCookie.GetCookieInternal(new Uri(StaticStrings.UrlIora), false);
WebClient wc = new WebClient();
wc.Encoding = System.Text.Encoding.UTF8;
wc.Headers.Add("Cookie:" + cookies);
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
wc.UseDefaultCredentials = true;
string uri = "";
uri = StaticStrings.UrlIora + name;
var myJsonResponse = wc.DownloadString(uri);
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
string signame = myDeserializedClass.ToString();
return signame;
}
}
在JSON中定义变量的代码:
namespace TimeSheet_Try11_Models
{
public class Employeename
{
public string signature { get; set; }
public string firstName { get; set; }
public string fullName { get; set; }
public string lastName { get; set; }
}
public class Root
{
public List<Employeename> Employeename { get; set; }
}
}
我不会亲自将文本框换成组合框来提供自动完成,我会将文本框的AutoCompleteMode
设置为例如SuggestAppend
,并将其AutoCompleteSource
设置为例如CustomSource
,然后将其AutoCompleteCustomSource
设置为一个AutoCompleteStringCollection
,该AutoCompleteCustomSource
,该
var acsc = new AutoCompleteStringCollection();
acsc.Add("Jane Doe"); // value from API perhaps?
acsc.Add("John Smith"); // value from API query all
当用户让文本框帮助他们写名字时,这个名字可以提交给API来加载其余的用户信息
一个组合可能会提前工作;下载所有的数据,选择其中的一些在组合中显示,其余的保留在后面的代码中供访问。