I would like to know how to deserialize a json array and display it on a richTextbox. I'm calling an API to get the JSON array. 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
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
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:
[{'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.
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.
var results = JsonConvert.DeserializeObject<dynamic>(jsonArray);
Now you cane access results[0].Name
.
Alternatively you can return object of type 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.