簡體   English   中英

使用 RestSharp 客戶端反序列化嵌套的 JSON

[英]Deserialize nested JSON with RestSharp Client

我想使用 REST Api 並反序列化嵌套的 JSON 響應。 我使用 json2csharp.com 創建了這些類。

JSON 消耗

{
  id: 32,
  name: "test supply object",
  formId: 4,
  sortOrder: 0,
  created: 1572902163907,
  creator: "jsingler",
  attributes: [
    {
      id: 144,
      attribute: {
        attributeName: "Description",
        attributeType: "TextArea",
        id: 8
      },
      attributeValue: "for development testing. do not delete or use."
    },
    {
      id: 145,
      attribute: {
        attributeName: "Quantity",
        attributeType: "NumberLong",
        id: 10
      },
      attributeValue: "4"
    }
  ]
}

JSON2CSHARP.COM output

public partial class Asset
{
    [JsonProperty(PropertyName = "id")]
    public int id { get; set; }
    [JsonProperty(PropertyName = "name")]
    public string name { get; set; }
    [JsonProperty(PropertyName = "formId")]
    public int formId { get; set; }
    [JsonProperty(PropertyName = "sortOrder")]
    public int sortOrder { get; set; }
    [JsonProperty(PropertyName = "created")]
    public long created { get; set; }
    [JsonProperty(PropertyName = "creator")]
    public string creator { get; set; }
    public List<Attribute> attributes { get; set; }
}

public partial class Attribute
{
    [JsonProperty(PropertyName = "ida")]
    public int id { get; set; }
    [JsonProperty(PropertyName = "attribute")]
    public List<Attribute1> attribute { get; set; }
    [JsonProperty(PropertyName = "attributeValue")]
    public string attributeValue { get; set; }
}

public partial class Attribute1
{
    [JsonProperty(PropertyName = "attributeName")]
    public string attributeName { get; set; }
    [JsonProperty(PropertyName = "attributeType")]
    public string attributeType { get; set; }
    [JsonProperty(PropertyName = "ida1")]
    public int id { get; set; }
}

消費API數據的方法

public static List<Asset> GetAllAssets()
{
    var client = new RestClient("URL_USED");
    var request = new RestRequest();
    client.Authenticator = new HttpBasicAuthenticator("USERNAME", "PW");
    var response = new RestResponse();
    Task.Run(async () =>
    {
        response = await GetResponseContentAsync(client, request) as RestResponse;
    }).Wait();

    var AssetList = JsonConvert.DeserializeObject<List<Asset>>(response.Content);

    return AssetList;
}

這總是錯誤: An unhandled exception occurred while processing the request. JsonSerializationException: Cannot deserialize the current JSON object (eg {"name":"value"}) into type 'System.Collections.Generic.List`1[PVF_Web.Models.Attribute1]' because the type requires a JSON array (eg [1,2,3]) to deserialize correctly. To fix this error either change the JSON to a JSON array (eg [1,2,3]) or change the deserialized type so that it is a normal .NET type (eg not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. Path '[0].attributes[0].attribute.attributeName', line 1, position 158. An unhandled exception occurred while processing the request. JsonSerializationException: Cannot deserialize the current JSON object (eg {"name":"value"}) into type 'System.Collections.Generic.List`1[PVF_Web.Models.Attribute1]' because the type requires a JSON array (eg [1,2,3]) to deserialize correctly. To fix this error either change the JSON to a JSON array (eg [1,2,3]) or change the deserialized type so that it is a normal .NET type (eg not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. Path '[0].attributes[0].attribute.attributeName', line 1, position 158.

然后當我能夠讓 JSON 反序列化時,它不會返回屬性(應用程序的真正目的)。

任何建議或想法將不勝感激。

編輯 1

[HttpPut]
public void Send(Asset newJA, int Qty)
{
    var client = new RestClient("URL_TO_USE" + newJA.id + ".json");
    var request = new RestRequest("", Method.PUT);
    request.AddObject(newJA);

    client.Authenticator = new HttpBasicAuthenticator("USERNAME", "PW");
    client.ExecuteAsync(request, response => {
          Console.WriteLine(response.Content);
          Debug.WriteLine(response.Content);
     });
}

這總是失敗。

您的 JSON 無效。 Go 到https://jsonformatter.curiousconcept.com/並檢查所有錯誤。

屬性名稱必須在引號之間,如果您希望它是一個數組,則需要使其成為一個數組,將方括號 - [ ] - 添加到 json 的開頭和結尾。

首先確保您的 json 有效。 你可以看看這邊json 屬性必須在引號內"" 像這樣

“ID”

.

除此之外,您的根 object 不是列表。 因此,您必須將反序列化代碼更改為:

var AssetList = JsonConvert.DeserializeObject<Asset>(response.Content);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM