0

我有一个来自 API 的 JSON 响应,其中包含许多数据。我真正需要的只是结果中的一些项目。有没有一种方法可以将其反序列化为 C# 对象,而无需定义一个具有成员的类以与返回的 JSON 中的所有项目相对应。或者,我是否必须定义一个具有与返回的 JSON 中的所有成员元素相对应的属性的类?

这是返回的 JSON 示例

{"status":"success","message":"Tx Fetched","data":{"txid":993106,"txref":"rgdk3viu.h","flwref":"FLW-MOCK-08efd1cb507f60ae50f7ebab4b27d234","devicefingerprint":"1d3d89c867abc0a84e1e167e2430456a","cycle":"one-time","amount":240,"currency":"NGN","chargedamount":243.36,"appfee":3.36,"merchantfee":0,"merchantbearsfee":0,"chargecode":"00","chargemessage":"Please enter the OTP sent to your mobile number 080****** and email te**@rave**.com","authmodel":"PIN","ip":"197.211.58.150","narration":"CARD Transaction ","status":"successful","vbvcode":"00","vbvmessage":"successful","authurl":"N/A","acctcode":null,"acctmessage":null,"paymenttype":"card","paymentid":"6490","fraudstatus":"ok","chargetype":"normal","createdday":0,"createddayname":"SUNDAY","createdweek":1,"createdmonth":0,"createdmonthname":"JANUARY","createdquarter":1,"createdyear":2020,"createdyearisleap":true,"createddayispublicholiday":0,"createdhour":17,"createdminute":40,"createdpmam":"pm","created":"2020-01-05T17:40:50.000Z","customerid":248784,"custphone":"080123456789","custnetworkprovider":"UNKNOWN PROVIDER","custname":"Chukwuemeka Ekeleme","custemail":"emeka.ekeleme@gmail.com","custemailprovider":"GMAIL","custcreated":"2020-01-05T17:40:50.000Z","accountid":85976,"acctbusinessname":"Learning Suite Nigeria","acctcontactperson":"Joshua Ndukwe","acctcountry":"NG","acctbearsfeeattransactiontime":0,"acctparent":1,"acctvpcmerchant":"N/A","acctalias":null,"acctisliveapproved":0,"orderref":"URF_1578246050675_7111835","paymentplan":null,"paymentpage":null,"raveref":"RV31578246049488BB4A178915","amountsettledforthistransaction":240,"card":{"expirymonth":"09","expiryyear":"22","cardBIN":"553188","last4digits":"2950","brand":" CREDIT","issuing_country":"NIGERIA NG","card_tokens":[{"embedtoken":"flw-t1nf-4542d3a9e7155f1512344b02aaa46255-m03k","shortcode":"534fb","expiry":"9999999999999"}],"type":"MASTERCARD","life_time_token":"flw-t1nf-4542d3a9e7155f1512344b02aaa46255-m03k"},"meta":[]}}

我试过下面的代码

 using (var httpClient = new HttpClient())
        {
            StringContent content = new StringContent(JsonConvert.SerializeObject(paymentVerificationRequestData), Encoding.UTF8, "application/json");

            using (var response = await httpClient.PostAsync(paymentVerificationRequestData.Url, content))
            {
                string apiResponse = await response.Content.ReadAsStringAsync();
                var paymentVerificationResponse = JsonConvert.DeserializeObject<RaveVerificationResponseData>(apiResponse);
                string msg = paymentVerificationResponse.chargemessage;

                return Content(msg);

            }
        }

但是 paymentVerificationResponse 中的所有元素,包括 chargemessage 都是 null 或 0

我的应用程序在 ASP.Net-Core 3.1 上运行

4

3 回答 3

2

您不需要有一个对应于 Json 中所有属性的类,您可以只创建一个具有所需属性的类并对其进行反序列化。

public class Result
{
    public string Status { get; set;}
    public string Message { get; set;}
}

var result = JsonConvert.DeserializeObject<Result>(json);
于 2020-01-05T18:34:29.460 回答
1

使用以下方法解析 json 字符串:

var json = JObject.Parse("JsonString");

然后您可以使用访问每个密钥var status = (StatusEnum)json["yourKey"]

或者,如果您不确定密钥是否始终存在,您可以使用

json.ContainsKey("yourKey")

或者您可以尝试立即解析它

if (json.TryGetValue("yourKey", out var yourKey))
{
   //property found
   var yourProperty = (YourType)yourKey;
}
else
{ 
   //doesn't contain the property
}

甚至通过使用

if (json["yourKey"] != null)
{
   //property found
}

希望这可以帮助。

于 2020-01-05T18:41:36.630 回答
0

api 响应是一个嵌套对象。你有一些选择。您可以使用object和访问密钥Reflection。例如chargemessage

var deserializedObject = JsonConvert.DeserializeObject<object>(json);
var data = deserializedObject.GetType().GetProperty("data").GetValue(deserializedObject);
var chargemessage = data.GetType().GetProperty("chargemessage").GetValue(data);

另一种选择是使用您需要的键定义一个类,并使用 with 反序列化 JSON。

public class MyClass
{
    public DataClass data { get; set;}
}
public class DataClass
{
    public string chargemessage { get; set;}
}

反序列化后,您可以访问如下值:

var deserializedObject = JsonConvert.DeserializeObject<MyClass>(json);
var status = deserializedObject.data.chargemessage;
于 2020-01-05T18:32:56.537 回答