C# 从返回的 json 对象中获取值

C# get a value from a returned json object

所以我正在尝试检查从 api 调用活动活动返回给我的值。 因为我正在学习 C#,所以我不确定该怎么做。

所以我使用此代码发送 api 调用并将响应存储在变量中:

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

然后我使用这个在 visual studio 中输出对输出 wibndow 的响应:

System.Diagnostics.Debug.WriteLine(contactExists);

这个returns这个:

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

现在在 C# 中,我将如何检查此 "result_code":1

的值

我遇到了 this anwswer 并检查了 msdn,但它没有意义。

我也认为 contactExists.result_code 可能会起作用,但它不起作用。

任何人都知道如何去做。 干杯

我推荐你使用Json.NET:

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

所以你可以像这样轻松使用:

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

希望对你有所帮助:)

创建适当的泛型 class

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

最后使用JSON反序列化

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

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

您还可以使用以下代码。在这里你可以通过使用 JObject class of Json.Net..

来做到这一点
var jsonResult = acs.SendRequest("POST", getParameters1, postParameters1);

JObject contactExists = JsonConvert.DeserializeObject(jsonResult);

现在要访问上述 json 对象的属性,您可以像这样使用:-

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