简体   繁体   English

无法将 JSON 字符串反序列化为 C# Object

[英]Unable to deseralize JSON String to a C# Object

Im trying to convert a JSON string retrived from https://my-json-server.typicode.com/dskato/UDLAProyectoApi/posts to a list of my "Customer" object我试图将从https://my-json-server.typicode.com/dskato/UDLAProyectoApi/posts 检索到的 JSON 字符串转换为我的“客户”列表 ZA8CFFDE6331BD59EB666C9

The data is coming good but when i try to deserialize, nothing happens, the data is not null but unable to print it with System.Diagnostics.Debug.WriteLine();数据很好,但是当我尝试反序列化时,没有任何反应,数据不是 null 但无法使用 System.Diagnostics.Debug.WriteLine(); to se what it's going on看看发生了什么

My Models: Customer.cs我的模型:Customer.cs

 public class Customer
{
    private CustomerType _customerType;

    public int Id { get; set; }
    public string Name { get; set; }
    public string Title { get; set; }
    public string Phone { get; set; }
    public string Address { get; set; }
    public string Description { get; set; }
    public double Longitude { get; set; }
    public double Latitude { get; set; }
    public DateTime? FullyAttendedTime { get; set; }
    public Geoposition GeoLocation => new Geoposition { Latitude = Latitude, Longitude = Longitude };
   
    public CustomerStatus CurrentStatus
    {
        get
        {
            return CustomerStatus.Resolving;
        }
    }

    public CustomerType CustomerCategory
    {
        get { return _customerType; }
        set { _customerType = value; }
    }
}

CustomStatus.cs自定义状态.cs

public enum CustomerStatus
{
    AwaitingTaxi = 1,
    Resolving = 2,
    Resolved = 3
}

CustomerType.cs客户类型.cs

   public enum CustomerType
{
    Business = 1,
    Group = 2,
    Anonymous = 3
}

My Data: DataRepository.cs我的数据:DataRepository.cs

 public static class DataRepository
{

    private static string _content;
    private static IList<Customer> _customerList;

    public static IList<Customer> LoadCustomerData()
    {
        //WriteFile();



        return _customerList ?? 
             (_customerList = 
             LoadData<IList<Customer>>(GlobalSetting.CustomerJsonDataFile));
    }



    public static async Task WriteFile()
    {
        string content = await LoadDataTest();
        _content = content;
        System.Diagnostics.Debug.WriteLine(content);
        System.Diagnostics.Debug.WriteLine("AAAAAAAAAAAAHHHHH");
        


    }

    static async Task<string> LoadDataTest()
    {
        var request = new HttpRequestMessage();
        request.RequestUri = new System.Uri("https://my-json-server.typicode.com/dskato/UDLAProyectoApi/posts");
        request.Method = HttpMethod.Get;
        request.Headers.Add("Accept", "application/json");
        var client = new HttpClient();

        HttpResponseMessage response = await client.SendAsync(request);

        if (response.StatusCode == System.Net.HttpStatusCode.OK)
        {
            string content = await response.Content.ReadAsStringAsync();
            return content;

        }
        else
        {

            return "";

        }



    }





    private static T LoadData<T>(string dataFileName)
    {


        
        var assembly = typeof(DataRepository).GetTypeInfo().Assembly;
        string preparedDataFileName = string.Format("MyTaxiCompany02.{0}",
            dataFileName.Replace("/", "."));
        Stream stream = assembly.GetManifestResourceStream(preparedDataFileName);

        if (stream == null)
        {
            return default(T);
        }

        using (StreamReader sr = new StreamReader(stream))
        {
         
            var ret = JsonConvert.DeserializeObject<T>(sr.ReadToEnd());
            System.Diagnostics.Debug.WriteLine("DATAA");
            System.Diagnostics.Debug.WriteLine(ret);
            return ret;

        }
      
    

    }
}

So what i tried was this:所以我尝试的是这样的:

private static T LoadData<T>(){

    var ret = JsonConvert.DeserializeObject<T>(_content);
    return ret;
    }


public static IList<Customer> LoadCustomerData()
    {


        return _customerList ?? 
             (_customerList = 
             LoadData<IList<Customer>>());
    }

But nothing happens但什么也没有发生

The LoadData Original is Working and Only Reads from a file in my project but what i need is to read the info coming from that Api LoadData Original 正在工作并且仅从我的项目中的文件中读取,但我需要的是读取来自该 Api 的信息

In the method LoadDataTest() is working ok and i call them in write file o get a string like this:在方法 LoadDataTest() 工作正常,我在写入文件中调用它们 o 得到这样的字符串:

  {
    "Id": 1,
    "Phone": "(555) XXX-XXXX",
    "Name": "Jhon Doe",
    "Title": "Jhon Doe",
    "Address": "Calle Dr. Miguel Ríos Sarmiento, 3, 41020 Sevilla, Spain",
    "Description": "Quick business trip to city center.",
    "UpdateDescription": "",
    "Latitude": -0.1674027763646159,
    "Longitude": -78.47094603889924,
    "CustomerType": 1,
    "Taxis": [
      {
        "id": 3
      }
    ],
    "CustomerCategory": 1
  },
  {
    "Id": 2,
    "Phone": "(555) XXX-XXXX",
    "Name": "Anna Doe",
    "Title": "Anna Doe",
    "Address": "Av. del Deporte, 33, 41020 Sevilla, Spain",
    "Description": "You need to go to the nearest hospital.",
    "UpdateDescription": "",
    "Latitude": -0.1698626865861518,
    "Longitude": -78.47514771904376,
    "Taxis": [
      {
        "id": 3
      }
    ],
    "CustomerCategory": 2
  },
  {
    "Id": 3,
    "Phone": "(555) XXX-XXXX",
    "Name": "Jhon Doe",
    "Title": "Jhon Doe",
    "Address": "Calle Dr. Miguel Ríos Sarmiento, 3, 41020 Sevilla, Spain",
    "Description": "Quick business trip to city center.",
    "UpdateDescription": "",
    "Latitude": -0.16288897268889635,
    "Longitude": -78.47435378522721,
    "CustomerType": 1,
    "Taxis": [
      {
        "id": 3
      }
    ],
    "CustomerCategory": 3
  }
] ``` 

Given给定

public class SomeFunkyClass
{
   public int Id { get; set; }
   public string Phone { get; set; }
   public string Name { get; set; }
   public string Title { get; set; }
   public string Address { get; set; }
   public string Description { get; set; }
   public string UpdateDescription { get; set; }
   public float Latitude { get; set; }
   public float Longitude { get; set; }
   public int CustomerType { get; set; }
   public Taxi[] Taxis { get; set; }
   public int CustomerCategory { get; set; }
}

public class Taxi
{
   public int id { get; set; }
}

You would simply call您只需致电

var results = JsonConvert.DeserializeObject<SomeFunkyClass[]>(input);

// or

var results = JsonConvert.DeserializeObject<List<SomeFunkyClass>>(input);

As to the WriteLine problem,至于WriteLine问题,

foreach (var item in result)
   Console..WriteLine($"id : {item.Id}, Name : {item.Name}...");

Output Output

id : 1, Name : Jhon Doe..
id : 2, Name : Anna Doe..
id : 3, Name : Jhon Doe..

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM