从Windows窗体的文本框中获取一个特定的字符串
本文关键字:一个 字符串 获取 窗体 Windows 文本 | 更新日期: 2023-09-27 18:18:51
我写了一个程序,用户输入一个地址,点击一个链接标签,程序就会把网站上的文本下载到一个文本框中。
代码是这样的:
private void llbMap_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
var _address = txtAddress.Text + " " + txtCity.Text + " " + "NY " + txtZip.Text;
txtFullAddress.Text = _address.ToString();
string toolDistanceMeasuring = "https://mywebsite.net/distance/?Type=json&Token=TUdBIFN5c3RlbXM1&Address=" + _address;
WebClient wc = new WebClient();
byte[] raw = wc.DownloadData(toolDistanceMeasuring);
string webData = Encoding.UTF8.GetString(raw);
txtWebData.Text = webData.ToString();
}
当用户单击LinkLabel时,txtWebData将被填充:
{
"status":"OK",
"fromlatitude":40.86791,
"fromlongitude":-73.428906,
"locationtype":"ROOFTOP",
"distancecoastmiles":1.7,
"closestdistancelatitude":40.8704815141,
"closestdistancelongitude":-73.4612902712,
"elevationstart":91.9,
"elevationend":0
}
我想知道如何从文本框中提取"distancecastmiles"并将该数据放入另一个文本框中。你知道我该怎么做吗?
您得到一个json
对象。您可以定义您的自定义类:
internal class Data
{
public float distancecoastmiles;
}
并将此字符串反序列化为object:
var s = new JavaScriptSerializer();
var o = s.Deserialize<Data>(webData.ToString());
var value = o.distancecoastmiles;
也可以从字符串中提取其他值,只需向Data
类添加新字段。
这显然是一个JSON,但如果你想使用textBox的Text属性来检索它,你也可以这样做:
var arrItems = txtWebData.Text.Split(",");
string coastmiles = "";
foreach (var item in arrItems)
{
if(item.Contains(distancecoastmiles))
{
var subarr = item.Split(":");
coastmiles = item.Last();
}
}
您正在检索的文本是JSON。解析它最简单的方法是解析它到JsonObject并访问distancecoastmiles
属性。
dynamic d = JObject.Parse(txtWebData.Text);
txtSomeOther.Text = d.distancecoastmiles;
参考:使用Json.net将json对象反序列化为动态对象
注意JObject是Json的一部分。. Net,您可以使用NuGet将其添加到您的项目中。
这是一个VB。Net 4.5+版本,引用/import文档:
Public Class Locat ' generated on http://jsonutils.com/
Public Property status As String
Public Property fromlatitude As Double
Public Property fromlongitude As Double
Public Property locationtype As String
Public Property distancecoastmiles As Double
Public Property closestdistancelatitude As Double
Public Property closestdistancelongitude As Double
Public Property elevationstart As Double
Public Property elevationend As Integer
End Class
Private Sub Button11_Click(sender As Object, e As EventArgs) Handles Button11.Click
'project reference to .Net System.Web.Extensions
'Imports System.Web.Script.Serialization
Dim jSerializer As New JavaScriptSerializer()
Dim strData2 = <j>
{
"status":"OK",
"fromlatitude":40.86791,
"fromlongitude":-73.428906,
"locationtype":"ROOFTOP",
"distancecoastmiles":1.7,
"closestdistancelatitude":40.8704815141,
"closestdistancelongitude":-73.4612902712,
"elevationstart":91.9,
"elevationend":0
}
</j>.Value
Try
Dim o As Locat = jSerializer.Deserialize(Of Locat)(strData2)
MsgBox(o.distancecoastmiles)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub