Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserializing JSON with indexed array in c#

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?

like image 360
Crossems Avatar asked Dec 05 '12 18:12

Crossems


2 Answers

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.

like image 116
Guvante Avatar answered Sep 23 '22 03:09

Guvante


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; }
}
like image 41
Alex Filipovici Avatar answered Sep 23 '22 03:09

Alex Filipovici