【问题标题】:Deseriaize Json from WebAPI using HttpClient使用 HttpClient 从 Web API 反序列化 Json
【发布时间】:2023-03-14 13:02:01
【问题描述】:

我从 WebAPI 返回以下 Json 格式。你们能帮忙反序列化吗?

{
  "@odata.context":"http://....... ","value":[
    **{
      "RecordNumber":"LDxxxx","RecordType":"Loan","PropertyAddress":{ "Address1":"601 xxxx","Address2":null,"Zip":"99999","City":"abc","State":"ab","County":"abcd" }
        ,"Summary":{ "BorrowerName":null,"ProductCode":null,"Status":"Not Registered" }
    }**,{
            "RecordNumber":"LDxxxx","RecordType":"Loan","PropertyAddress":{ "Address1":"601 xxxx","Address2":null,"Zip":"99999","City":"abc","State":"ab","County":"abcd" }
        ,"Summary":{ "BorrowerName":null,"ProductCode":null,"Status":"Not Registered" }
      },
….]
 }

我需要 value 元素中的内容。粗体是从 API 返回中重复的内容。我创建了一个符合以下描述的类。

public class RootObject
{
    [JsonProperty(PropertyName = "RecordNumber")]
    public string RecordNumber { get; set; }

    [JsonProperty(PropertyName = "RecordType")]
    public string RecordType { get; set; }

    [JsonProperty(PropertyName = "PropertyAddress")]
    public PropertyAddress PropertyAddress { get; set; }

    [JsonProperty(PropertyName = "Summary")]
    public Summary Summary { get; set; }
}

能够使用以下方法跳过 Json 数组中的第一条记录,获得“值”部分....但未能成功检索“值”对象

var dict = JsonConvert.DeserializeObject<Dictionary<string, object>>(forecast);
foreach (var kv in dict.Skip(1))
{
     JArray jsonVal = JArray.Parse(kv.Value.ToString());
}

感谢您的帮助。

萨提亚

【问题讨论】:

  • 这真的是准确的 JSON 吗?与** 和所有?
  • Maccettura...不,我把它们放在那里,只是为了表示相同格式的重复。

标签: c# .net json


【解决方案1】:

您可以反序列化为具体的类(在 http://json2csharp.com/ 的帮助下)

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

public class SOTest
{
    public class PropertyAddress
    {
        public string Address1 { get; set; }
        public object Address2 { get; set; }
        public string Zip { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string County { get; set; }
    }

    public class Summary
    {
        public object BorrowerName { get; set; }
        public object ProductCode { get; set; }
        public string Status { get; set; }
    }

    public class Value
    {
        public string RecordNumber { get; set; }
        public string RecordType { get; set; }
        public PropertyAddress PropertyAddress { get; set; }
        public Summary Summary { get; set; }
    }

    public class Result
    {
        [JsonProperty("@odata.context")]
        public string Context { get; set; }
        public List<Value> Value { get; set; }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-23
    • 1970-01-01
    • 2012-12-26
    • 2014-04-27
    • 1970-01-01
    相关资源
    最近更新 更多