问题描述
我是Visual Studio的新手。我正在编写一个程序,当输入员工姓名并单击“获取用户”按钮时,它将从API中检索员工的签名(例如,如果输入了员工姓名Jane Doe,将从以下位置检索签名“ JNDO” API字符串)。
使用文本框输入名称时,将成功读取所需的信息。但是,当我用组合框替换文本框以在用户键入时建议名称时,出现以下错误:
Newtonsoft.Json.JsonReaderException:'遇到意外字符 而解析值:
通过使用断点来了解值,它指出
字符串不是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
,该API是通过类似API的方式构建的,并以所有名称的列表作为响应
var acsc = new AutoCompleteStringCollection();
acsc.Add("Jane Doe"); // value from API perhaps?
acsc.Add("John Smith"); // value from API query all
当用户让texbox帮助他们输入名称时,可以将该名称提交给API以加载其余的用户信息
组合将提前工作;下载所有数据,选择其中一些要显示在组合中的内容,并将其余的保留在代码中以供访问。