DylanBro
DylanBro

Reputation: 15

Deserializing Web Json

I'm trying to deserialize the json string to objects and then write it to a richtextbox

 public void Form1_Load(object sender, EventArgs e)
    {

        using (var webClient = new System.Net.WebClient())
        {
            var json = webClient.DownloadString("https://opskins.com/api/user_api.php?request=GetOP&key=16a70bbdbcbae2e1574c18a5746046");

            var jarray = JsonConvert.DeserializeObject<Result>(json);

            richTextBox1.Text = jarray.op;


        }
    }

Class:

public class Result
{
    public string op { get; set; }
}

public class RootObject
{
    public Result result { get; set; }
}

Upvotes: 0

Views: 720

Answers (1)

Svek
Svek

Reputation: 12848

Mapping the object properly.

Your issue is because you are not mapping the JSON object properly to your Result class.

If we use your current link https://opskins.com/api/user_api.php?request=GetOP&key=foo

The object we get returned back in JSON is like this:

{
    "result": {
        "code": 401,
        "error": "API key does not exist"
    }
}

Which would mean the class you would map it to would look like this

public class Result
{
    public int Code { get; set; }  // note this is an int
    public string Error{ get; set; }
}

Mapping the object properly (to your textbox).

In the event that you want to map it to your text box.

using (var webClient = new System.Net.WebClient())
{
    var json = webClient.DownloadString(@"https://your-uri-goes-here");
    var data = JsonConvert.DeserializeObject<Result>(json);

    richTextBox1.Text = data.Error; // this will work because Error is of type string
}

Note that there is an @ in front of the URI string. As API keys may likely contain special characters that make need to be escaped.

If you wish to map a Type that is not a string, make sure you do a conversion for it, in some cases .ToString() will be sufficient.

Upvotes: 1

Related Questions