I'm very new to working with JSON and am dealing wtih a return from an API which I can't change the formatting of. The return example is : (actual urls have been removed)
{
"body":
{
"link":
{"linkurl": ["www.google.com"]}
},
"error": null,
"message": "Data Retrieved successfully",
"status": true
}
I am using the Newtonsoft.Json library with MVC 3, in VS2010.
My class is:
[JsonObject(MemberSerialization.OptIn)]
public class LinksJSON
{
[JsonProperty]
public string link{ get; set; }
[JsonProperty]
public string message { get; set; }
[JsonProperty]
public string error { get; set; }
[JsonProperty]
public bool status { get; set; }
}
I'm deserializing it with :
private static T _download_serialized_json_data<T>(string url) where T : new()
{
using (var w = new WebClient())
{
var json_data = string.Empty;
// attempt to download JSON data as a string
try
{
json_data = w.DownloadString(url);
}
catch (Exception) { }
// if string with JSON data is not empty, deserialize it to class and return its instance
return !string.IsNullOrEmpty(json_data) ? JsonConvert.DeserializeObject<T>(json_data) : new T();
}
}
public string CheckJSONLink()
{
var url = "<api url-removed for security>";
var outObj = _download_serialized_json_data<LinksJSON>(url);
return outObj.Link;
}
However I'm trying to get the value of linkurl
, which is an indexed array within Link
.
How would I access this information?
You did not setup your class to match the JSON, your class says that link
is a simple string, you your example shows it as a complex type.
In order to properly deserialize it as you expect, you will have to modify your class to match the JSON. Specifically link
should be an instance of a class.
You should use the following classes:
[JsonObject(MemberSerialization.OptIn)]
public class LinksJSON
{
[JsonProperty]
public body body { get; set; }
[JsonProperty]
public string message { get; set; }
[JsonProperty]
public string error { get; set; }
[JsonProperty]
public bool status { get; set; }
}
[JsonObject(MemberSerialization.OptIn)]
public class body
{
[JsonProperty]
public link link { get; set; }
}
[JsonObject(MemberSerialization.OptIn)]
public class link
{
[JsonProperty]
public string[] linkurl { get; set; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With