简体   繁体   中英

C# JSON Deserialization Dictionary Exception

I need help with JSON parsing in C#. There is my JSON string I am trying to parse and to work with. I do not want to create a class to instantiate the object, because there can be more calls with a lot of returning object type - Tournament, Team, User, etc.

{
    "response":{
        "2":{
            "tournament_id":2,
            "created_at":{
                "date":"2015-11-09 21:01:06",
                "timezone_type":3,
                "timezone":"Europe/Prague"
            },
            "creator_id":1,
            "name":"Tournament Test #1",
            "desc":"...!",
            "state":0,
            "is_visible":1
        },
        "3":{
            "tournament_id":3,
            "created_at":{
                "date":"2015-11-09 21:01:06",
                "timezone_type":3,
                "timezone":"Europe/Prague"
            },
            "creator_id":1,
            "name":"Tournament Test #2",
            "desc":"...",
            "state":1,
            "is_visible":1
        }
    },
    "error":false
}

I am using JSON.net library to parse JSON string and this is C# code I am using in my program:

public class API
    {
        private WebClient client;

        protected string auth_key   = "xxx";
        protected string base_url   = "http://127.0.0.1/tournaments_api/www/";
        private string endpoint_url = "";
        private string url_params   = "";

        public string url_data;
        public Dictionary<string, string>[] data;

        public bool success = false;
        public string errorMessage = "";
        public int errorCode = 0;

        public API()
        {
            this.client = new WebClient();
        }

        private void Request()
        {

            string url = this.base_url + this.endpoint_url + "/" + this.auth_key + "?" + this.url_params;
            this.url_data = this.client.DownloadString(url);
            Console.WriteLine(this.url_data);

            this.data = JsonConvert.DeserializeObject<Dictionary<string, string>[]>(this.url_data);
        }
    }

There is this problem with parsing:

An unhandled exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll

Additional information: Cannot deserialize the current JSON object (eg {"name":"value"}) into type 'System.Collections.Generic.Dictionary`2[System.String,System.String][]' because the type requires a JSON array (eg [1,2,3]) to deserialize correctly.

To fix this error either change the JSON to a JSON array (eg [1,2,3]) or change the deserialized type so that it is a normal .NET type (eg not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.

Path 'response', line 1, position 12.

Thanks for your help! :)

Your JSON is an object, which in C# can be deserialized as Dictionary<string, object> . However, you try to deserialize it as an array, while there are absolutely no arrays.

You need to change this to:

public Dictionary<string, object>[] data;

// ...

JsonConvert.DeserializeObject<Dictionary<string, object>>(this.url_data);

At the same time, even after changing it, you won't be able to access the nested objects.

As you write that

I do not want to create a class to instantiate the object, because there can be more calls with a lot of returning object type - Tournament, Team, User, etc.

I may suggest to use dynamic :

dynamic data = JsonConvert.DeserializeObject(this.url_data);

Then, you will be able to work with it like with dynamic object:

var err = data.error;

At the same time, creating a classes to describe this model and to be used for deserializing this JSON sounds better for me.

Alternative to Yeldar Kurmangaliyev's answer is to use the built-in LINQ to JSON support of the JSON.NET library:

JObject jObject = JObject.Parse("-- JSON STRING --");

JToken response = jObject["response"];

bool error = jObject["error"].Value<bool>();

There are a lot of extensions methods that allow easy parsing of json strings.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM