[英]How to display a json array in a textbox using c#
I would like to know how to deserialize a json array and display it on a richTextbox. 我想知道如何反序列化json数组并将其显示在richTextbox上。 I'm calling an API to get the JSON array. 我正在调用一个API以获取JSON数组。 Can someone help me out with this. 有人可以帮我这个忙。 I have got it into a List but i'm not sure whether i've done it properly. 我已经将其列入清单,但是我不确定自己是否做得正确。
Form1.cs Form1.cs
private void btnStart_Click(object sender, EventArgs e)
{
runapi("http://localhost:8080/json_coordinates");
}
public void runapi(string api)
{
try
{
WebRequest request = WebRequest.Create(api);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string json = reader.ReadToEnd();
obj.DeserializeJsonDes(json);
// Help me fill it up to display data on the richTextBox
//richTextBox1.Text = responseFromServer;
reader.Close();
dataStream.Close();
response.Close();
}
catch (Exception ex)
{
}
}
Class JsonDes JsonDes类
class JsonDes
{
public List<JsonDes> name { get; set; }
public List<JsonDes> coordinates { get; set; }
public List<JsonDes> DeserializeJsonDes(string jsonArray)
{
//return JsonConvert.DeserializeObject<JsonDes>(json);
return JsonConvert.DeserializeObject<List<JsonDes>>(jsonArray);
}
}
The original JSON being passed in has the structure: 传入的原始JSON具有以下结构:
[{'name' : 'Train 1', 'coordinates' : '38.892802, -77.061945'},
{'name' : 'Train 2', 'coordinates' : '38.941686, -77.134043'}]
The easiest way would be first define your class to fit the shape of one record in the data being retrieved. 最简单的方法是首先定义您的类,使其适合要检索的数据中一条记录的形状。
In this case: 在这种情况下:
public class JsonDes
{
public string name { get; set;
public string coordinates { get; set; }
}
From there, you just need to use Newtonsoft's Json.NET to deserialize it. 从那里,您只需要使用Newtonsoft的Json.NET对其进行反序列化。
public static List<JsonDes> Convert(string json)
{
return JsonConvert.DeserializeObject<List<JsonDes>>(json);
}
Your class structure is not clear.However without knowing that I will try to answer the question. 您的课程结构不清楚。但是,不知道我将尝试回答这个问题。
What you can do is to cast a dynamic type like JsonConvert.DeserializeObject<dynamic>()
to deserialize this string into a dynamic type then simply access its properties in the usual way. 您可以做的是将动态类型JsonConvert.DeserializeObject<dynamic>()
以将该字符串反序列化为动态类型,然后以通常的方式简单地访问其属性。
var results = JsonConvert.DeserializeObject<dynamic>(jsonArray);
Now you cane access results[0].Name
. 现在,您可以访问results[0].Name
。
Alternatively you can return object of type JArray
. 或者,您可以返回JArray
类型的JArray
。
dynObj = (JArray)JsonConvert.DeserializeObject(jsonArray);
Then iterate over this object like 然后像这样遍历这个对象
foreach (JObject item in dynObj)
{
access now item["Your Property Name"]
}
Hope this helps you. 希望这对您有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.