我是否在GetProductAsync中错误地反序列化了我的JSON对象?

时间:2018-02-16 21:38:54

标签: c# json async-await httpclient

当我运行这段代码时,我收到以下错误消息:

无法将当前JSON数组(例如[1,2,3])反序列化为类型“HttpClientSample.Product”,因为该类型需要JSON对象(例如{“name”:“value”})才能正确反序列化。 要修复此错误,请将JSON更改为JSON对象(例如{“name”:“value”})或将反序列化类型更改为数组或实现集合接口的类型(例如ICollection,IList),例如List从JSON数组反序列化。 JsonArrayAttribute也可以添加到类型中,以强制它从JSON数组反序列化。

我以为我告诉我的客户端返回一个JSON ......我是否需要转换我的响应(JsonConvert.DeserializeObject)?如果是这样,到列表?

使用邮递员的典型回应是:

[
    {
        "id": "1",
        "name": "test",
        "inactive": false           
    },
    {
        "id": "2",
        "name": "test2",
        "inactive": false           
    }
]

谢谢

using Newtonsoft.Json;
using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;


namespace HttpClientSample
{
   public class Product
  {

    public string id { get; set; }
    public string name { get; set; }
    public bool inactive { get; set; }
  } 

class Program
{

    static HttpClient client = new HttpClient();

    static async Task<Product> GetProductAsync(string path)
    {
        Product product = null;
        HttpResponseMessage response = await client.GetAsync(path);
        if (response.IsSuccessStatusCode)
        {

            product = await response.Content.ReadAsAsync<Product>();
            Console.WriteLine("{0}\t${1}\t{2}", product.id, product.name, product.inactive);
        }
        return product;
    }


    static void Main()
    {
       // RunAsync().GetAwaiter().GetResult();
        RunAsync().Wait();
    }

    static async Task RunAsync()
    {


        // Update port # in the following line.
        var byteArray = Encoding.ASCII.GetBytes("user:pass");
        client.BaseAddress = new Uri("https://localhost:51075/api/products");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
        ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

        try
        {

            Product product = new Product();

            // Get the product
            product = await GetProductAsync("https://localhost:51075/api/products");

        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }

        Console.ReadLine();
    }
}

}

2 个答案:

答案 0 :(得分:0)

更新答案 :) GetResponseAsync函数:

public static async Task<SetupWebApiResponse> GetResponseAsync(string 
        endpoint)
    {

        string result = "";
        HttpResponseMessage response = await client.GetAsync(endpoint);
        if (response.IsSuccessStatusCode)
        {
            HttpContent content = response.Content;
            result = await content.ReadAsStringAsync();

        }
        return new SetupWebApiResponse(response.StatusCode, result);

    }

SetupWebApiResponse类:

public class SetupWebApiResponse
{
    public SetupWebApiResponse() { }

    public SetupWebApiResponse(int statusCode, object responseBody)
    {
        this.StatusCode = statusCode;
        this.ResponseBody = responseBody;
    }

    public SetupWebApiResponse(HttpStatusCode statusCode, object responseBody)
        : this((int)statusCode, responseBody)
    {
    }

    /// <summary>
    /// Gets or sets the HTTP status code of the response
    /// </summary>
    public int StatusCode { get; set; }

    /// <summary>
    /// Gets or sets the response body content
    /// </summary>
    public object ResponseBody { get; set; }
}

SetupWebAI类:

  public class SetupWebAPI
 {

    static string User;
    static string Password;
    static string Endpoint;
    static object Content;

    static SetupWebApiResponse apiResponse;

    public static SetupWebApiResponse GetResponseInStringFormat(string user, string password, string endpoint)
    {
        User = user;
        Password = password;
        Endpoint = endpoint;
        ExecuteResponse().Wait();
        return apiResponse;
    }
    private static async Task ExecuteResponse()
    {
        SetupWebAPIAsync.SetAPIAuthentication(User, Password);
        apiResponse = await SetupWebAPIAsync.GetResponseAsync(Endpoint);
    }

答案 1 :(得分:-2)

您的问题似乎是您的JSON数组格式不正确。为了让我的例子工作,我必须在}之后添加一个逗号,&lt;&lt;&lt; ---

这就是我的所作所为:

  • 复制JSON对象字符串文本
  • 在visual studio中,我使用“编辑|选择性粘贴|将JSON粘贴为类” -
  • 在命名空间部分内的新.cs文件中。

示例:

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ClassLibrary1
{
    public class Class1
    {
        public class Product
        {
            public string id { get; set; }
            public string name { get; set; }
            public bool inactive { get; set; }
        }

        public void testingClass()
        {
            string testJSONResponse = @"
    [{
                ""id"": ""1"",
        ""name"": ""test"",
        ""inactive"": false
    },]
";
            var myNewCSharpObject = JsonConvert.DeserializeObject<Product[]>(testJSONResponse);

        }
    }
}