Marcelo
Marcelo

Reputation: 1

Weird behavior with JsonConverter

So here's what's happening: I got this json string (after uploading an image to imgur by using their API):

{
    "data": {
        "id": "123456",
        "title": null,
        "description": null,
        "datetime": 1378731002,
        "type": "image/png",
        "animated": false,
        "width": 1600,
        "height": 900,
        "size": 170505,
        "views": 0,
        "bandwidth": 0,
        "favorite": false,
        "nsfw": null,
        "section": null,
        "deletehash": "qZPqgs7J1jddVdo",
        "link": "http://i.imgur.com/123456.png"
    },
    "success": true,
    "status": 200
}

I'm trying to deserialize to a Dictionary using JsonConvert.DeserializeObject like this:

richTextBox1.Text = json;
Dictionary<string, string> dic = JsonConvert.DeserializeObject<Dictionary<string, string>>( json );
MessageBox.Show( dic["success"].ToString() );

Thing is, I can see the json string on the RichTextBox, but the MessageBox after the JsonConvert never shows up... What am i missing here?

In fact, I can even put a breakpoint after the JsonCOnvert, it'll not be triggered. What's happening?

Thank you.

Upvotes: 0

Views: 86

Answers (2)

I4V
I4V

Reputation: 35363

I think you get an exception while deserialization. You can use this site and convert your json to a concrete class.

var obj = JsonConvert.DeserializeObject<RootObject>(json);

public class Data
{
    public string id { get; set; }
    public object title { get; set; }
    public object description { get; set; }
    public int datetime { get; set; }
    public string type { get; set; }
    public bool animated { get; set; }
    public int width { get; set; }
    public int height { get; set; }
    public int size { get; set; }
    public int views { get; set; }
    public int bandwidth { get; set; }
    public bool favorite { get; set; }
    public object nsfw { get; set; }
    public object section { get; set; }
    public string deletehash { get; set; }
    public string link { get; set; }
}

public class RootObject
{
    public Data data { get; set; }
    public bool success { get; set; }
    public int status { get; set; }
}

You can also use JObject, since it implemets IDictionary

var dic = JObject.Parse(json);
MessageBox.Show(dic["success"].ToString());

Upvotes: 2

Bananenbieger
Bananenbieger

Reputation: 101

Maybe you should try to use a Dictionary<string, object>, because the values aren't always strings. It seems like there is an exception, when you call the json deserializer.

Perhaps you can surround your code with a "try-catch" block in order to catch an exception.

Upvotes: 0

Related Questions