user3242355
user3242355

Reputation: 3

Trouble deserializing rather simple JSON data using JSON.NET

I have problem with deserializing some JSON data which looks like this:

{
    "Var1": 0,
    "Var2": 2,
    "Var3": -1,
    "Var4": 5,
    "Var5": 1,
    "Var6": 3
}

This is located on a remote server and I fetch it then deserialize using this method in a separate class:

public static T _download_serialized_json_data<T>() where T : new()
{
    using (var w = new WebClient())
    {
        var json_data = string.Empty;
        try
        {
            json_data = w.DownloadString("http://url_to_json_data.json");
        }
        catch (Exception) { }
        return !string.IsNullOrEmpty(json_data) ? JsonConvert.DeserializeObject<T>(json_data) : new T();
    }
}

My JSON class:

public class Variables
{
    public int Var1 { get; set; }
    public int Var2 { get; set; }
    public int Var3 { get; set; }
    public int Var4 { get; set; }
    public int Var5 { get; set; }
    public int Var6 { get; set; }
}

Then in a different class when I need to access the data, I do this:

List<JsonClass.Variables> VARS = JsonClass._download_serialized_json_data<List<JsonClass.Variables>>();

System.Console.WriteLine("Variable 1: " + VARS[0].Var1);

And in the last part I get a massive exception thrown in my face saying this:

Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Solution1.JsonClass+Variables]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

How would I properly access those simple integers without overdoing the thing? I tried dictionaries but that didn't work out too well. Thank you for your time.

Upvotes: 0

Views: 248

Answers (1)

Ben Allred
Ben Allred

Reputation: 4864

Try this instead

JsonClass.Variables VARS = JsonClass._download_serialized_json_data<JsonClass.Variables>();

System.Console.WriteLine("Variable 1: " + VARS.Var1);

You're original code was expecting to deserialize a list of JsonClass.Variables, but your example JSON only has a single object.

Upvotes: 4

Related Questions