将JSON字符串反序列化为C#中的非预定义对象

huangapple go评论80阅读模式
英文:

Deserializing JSON string to a non-predefined object in C#

问题

以下是您要翻译的部分:

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

这是返回的JSON示例

{"status":"success","message":"Tx Fetched","data":{...}}

我尝试了以下代码

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上"

请注意,我只翻译了您的问题和描述,没有翻译代码部分。如果您需要有关代码的帮助,请提出具体问题,我会尽力提供帮助。

英文:

I have a JSON response from an API with a number of data. What I actually need is just a few of the items in the result.
Is there a way I can deserialize it to a C# object without having to define a class with members to correspond with all the items in the returned JSON.
Or, must I have to define a class that has properties to correspond to all the member elements in the returned JSON?

This is a sample of the returned 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":[]}}

I have tried the following code

 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);

            }
        }

but all the elements in paymentVerificationResponse including chargemessage are all null or 0

My application is running on ASP.Net-Core 3.1

答案1

得分: 2

你不需要拥有与 JSON 中的 所有 属性对应的类,你可以只创建一个包含所需属性的类并进行反序列化。

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

var result = JsonConvert.DeserializeObject<Result>(json);
英文:

You don't need to have a class that corresponds to all properties in Json, you can create a class only with needed properties and deserialize it.

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

var result = JsonConvert.DeserializeObject&lt;Result&gt;(json);

答案2

得分: 1

解析 JSON 字符串的方法如下:

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

然后,您可以使用以下方式访问每个键:

var status = (StatusEnum)json["yourKey"];

如果您不确定键是否总是存在,可以通过以下方式进行检查:

if (json.ContainsKey("yourKey"))
{
    // 属性存在
}

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

if (json.TryGetValue("yourKey", out var yourKey))
{
   // 属性找到
   var yourProperty = (YourType)yourKey;
}
else
{ 
   // 不包含该属性
}

甚至可以通过以下方式进行检查:

if (json["yourKey"] != null)
{
   // 属性找到
}

希望这些信息对您有所帮助。

英文:

Parse the json string using:

var json = JObject.Parse(&quot;JsonString&quot;);

Then you can access each key using var status = (StatusEnum)json[&quot;yourKey&quot;]

Or if you are not sure if the key will always be present you can check by using

json.ContainsKey(&quot;yourKey&quot;)

or you can try parsing it right away

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

or even by using

if (json[&quot;yourKey&quot;] != null)
{
   //property found
}

Hope this helps.

答案3

得分: 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);

另一种选项是定义一个包含您需要的键的类,并使用它来反序列化 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;
英文:

The api response is a nested object. You have some options. You can use object and access to a key using Reflection. for example for chargemessage:

var deserializedObject = JsonConvert.DeserializeObject&lt;object&gt;(json);
var data = deserializedObject.GetType().GetProperty(&quot;data&quot;).GetValue(deserializedObject);
var chargemessage = data.GetType().GetProperty(&quot;chargemessage&quot;).GetValue(data);

Another option is defining a class with the keys that you need and deserializing the JSON using with.

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

after deserializing you can access the values like this:

var deserializedObject = JsonConvert.DeserializeObject&lt;MyClass&gt;(json);
var status = deserializedObject.data.chargemessage;

huangapple
  • 本文由 发表于 2020年1月6日 02:23:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/59602918.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定