0

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.

3
  • The sample data you have given is not an array, just one instance of the class. Are you sure it is an array (List)? Commented Jan 27, 2014 at 22:44
  • 2
    Looking at your examples the JSON only contains one object, not an array of objects so the generic argument for your download-method should be JsonClass.Variables, not List<JsonClass.Variables>. Commented Jan 27, 2014 at 22:44
  • The whole file is exactly what I have posted there. It doesnt contain the [ ] array brackets. Only { and }. Commented Jan 27, 2014 at 22:45

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.