简体   繁体   中英

C# get a value from a returned json object

So im trying to check a value which is returned to me from an api call to active campaign. Because I'm learning C# im not sure how to go about this.

So I use this code to send the api call and store the response in a variable:

var contactExists = acs.SendRequest("POST", getParameters1, postParameters1);

Then I output the response to the output wibndow in visual studio using this:

System.Diagnostics.Debug.WriteLine(contactExists);

This returns this:

{"result_code":1,"result_message":"Success: Something is returned","result_output":"json"}

Now in C# how would I check the value of this "result_code":1

I came across this anwswer and checked the msdn but it's not making sense.

I also thought maybe contactExists.result_code would work but it doesn't.

Anyone know how to go about this. Cheers

I recommend you to use Json.NET :

var jsonResult = acs.SendRequest("POST", getParameters1, postParameters1);
dynamic contactExists = JsonConvert.DeserializeObject(jsonResult);

So you can easily use just like this:

int result_code = contactExists.result_code;
string result_message = contactExists.result_message;

I hope to be helpful for you :)

You can also use the following peace of code. Here you can do this by using JObject class of Json.Net..

var jsonResult = acs.SendRequest("POST", getParameters1, postParameters1);

JObject contactExists = JsonConvert.DeserializeObject(jsonResult);

Now to access the properties from the above json object you can use like this:-

 int result_code = Convert.ToInt32(contactExists["result_code"]);

Create an appropriate generic class

public class Response<T>
{
    public int result_code { get; set; }
    public string result_message { get; set; }
    public T result_output { get; set; }
}

Finally use the JSON Deserialization

var jsonResult = acs.SendRequest("POST", getParameters1, postParameters1);

var result = JsonConvert.DeserializeObject<Response<string>>(jsonResult);

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