CS0029 Невозможно неявно преобразовать тип 'System.Collections.Generic.List'to' Models.JobModel ' - PullRequest
0 голосов
/ 16 мая 2019

Я пытаюсь запросить объект json из базы данных через API.Но возвращенный результат был jsonArray.Поэтому я пытаюсь преобразовать объект jsonArray в объект json для печати пользователю.

Я пробовал два разных метода, но он выдает ошибку.

Метод 1:

public static async Task<JobModel> LoadJobIndex1(string specificValue)//Posting Type
    {
        string url = $"https://data.cityofnewyork.us/resource/kpav-sd4t.json?$limit=1&posting_type={ specificValue }";

        using (HttpResponseMessage response = await ApiHelper.ApiHelper.ApiClient.GetAsync(url))
        {
            if (response.IsSuccessStatusCode)
            {
                var client = new WebClient();
                var result = client.DownloadString("https://data.cityofnewyork.us/resource/kpav-sd4t.json?$limit=1&level=1");

                JobResultModel results = JsonConvert.DeserializeObject<JobResultModel>(result);

            }
            else
            {
                throw new Exception(response.ReasonPhrase);
            }
        }
    }

Метод 2:

public static async Task<JobModel> LoadJobIndex2(string specificValue)//Job Difficulty
{
    string url = $"https://data.cityofnewyork.us/resource/kpav-sd4t.json?$limit=3&level={ specificValue }";

    using (HttpResponseMessage response = await ApiHelper.ApiHelper.ApiClient.GetAsync(url))
    {
        if (response.IsSuccessStatusCode)
        {
            JobResultModel result = await response.Content.ReadAsAsync<JobResultModel>();

            return result.Results;
        }
        else
        {
            throw new Exception(response.ReasonPhrase);
        }
    }
}

Я пытаюсь создать модель для хранения ответа.

public class JobResultModel
{
    public List<JobModel> Results { get; set; }
}

public class JobModel
{
    public string Business_title { get; set; }//Name of the job
    public string Posting_type { get; set; }//Internal/External
    public string Level { get; set; }//Diffculty of the job
    public string Full_time_part_time_indicator { get; set; }
    public string Salary_range_from { get; set; }
    public string Salary_range_to { get; set; }
    public string Job_description { get; set; }
    public string Minimum_qual_requirements { get; set; }
    public string Preferred_skills { get; set; }
    public string To_apply { get; set; }
}

После этого я пытаюсь распечатать результат для пользователя.

var job = await GetJobDialog.LoadJobIndex1(specficValue);
                        await context.PostAsync($"Job Search Result : {Environment.NewLine}{JsonConvert.SerializeObject(job)}");

Вот пример результата

[{

"business_title":"COLLEGE AIDE - CLERICAL",

"full_time_part_time_indicator":"P",

"job_description":"The Office of Collective Bargaining (OCB) is an independent, impartial governmental agency that resolves labor disputes between the City of New York and the City employees’ Unions.  OCB seeks a Clerical College Aide who will perform clerical and related work.    OCB’s College Aide will attend to the office’s reception desk, answering and routing telephone calls and directing visitors to the proper destination.  He or she will also perform clerical work in relation to records, files, invoices and reports using alphabetical and numerical procedures including data/control coding.    He or she will perform clerical operations in an assigned area, such as the filing of material and the searching of files for material difficult to locate.    He or she will also prepare reports requiring the selection of data from simple records or statistics, and check records for accuracy of information and for conformity with established policy and procedures.",

"level":"1",

"minimum_qual_requirements":"For Assignment Level I:  Matriculation at an accredited college or graduate school. Employment is conditioned upon continuance as a student in a college or graduate school.  For Assignment Level II (Information Technology):  Matriculation at an accredited college or graduate school. Employment is conditioned upon continuance as a student in a college or graduate school with a specific course of study in information technology, computer science, management information systems, data processing, or closely related field, including or supplemented by 9 semester credits in an acceptable course of study.  For Assignment Level III (Information Technology Fellow):  Matriculation at an accredited college or graduate school. Employment is conditioned upon continuance as a student in a college or graduate school with a specific course of study in information technology, computer science, management information systems, data processing, or other area relevant to the information technology project(s) assigned, including or supplemented by 9 semester credits in an acceptable course of study. Appointments to this Assignment Level will be made by the Technology Steering Committee through the Department of Information Technology and Telecommunications.    SPECIAL NOTE  Maximum tenure for all Assignment Levels in the title of College Aide is 6 years. No student shall be employed more than half-time in any week in which classes in which the student is enrolled are in session. Students may be employed full-time during their vacation periods.",

"posting_type":"Internal",

"preferred_skills":"1.\tExcellent interpersonal communication skills  2.\tStrong work ethic and attention to detail  3.\tFamiliarity with Microsoft Office Suite","process_date":"2019-05-14T00:00:00.000","residency_requirement":"New York City residency is generally required within 90 days of appointment. However, City Employees in certain titles who have worked for the City for 2 continuous years may also be eligible to reside in Nassau, Suffolk, Putnam, Westchester, Rockland, or Orange County. To determine if the residency requirement applies to you, please discuss with the agency representative at the time of interview.",

"salary_range_from":"8.75",

"salary_range_to":"10.36","title_code_no":"10209",

"to_apply":"Click the “Apply Nowâ€\u009d button.  While we appreciate every applicant’s interest, only those under consideration will be contacted.  Do not email, mail or fax your resume to OCB directly.  No phone calls will be accepted."

}]

1 Ответ

0 голосов
/ 16 мая 2019

Проблема в том, что модель JSON представляет собой саму коллекцию, а не объект с внутренней коллекцией с именем Results. Чтобы это исправить, нужно десериализовать в коллекцию JobModel.

var result = await response.Content.ReadAsAsync<List<JobModel>>();

Тогда вы можете просто вернуть первый элемент в списке

return result.FirstOrDefault();

ИЛИ измените ваш метод, чтобы он возвращал список JobModel и возвращал весь список

public static async Task<List<JobModel>> LoadJobIndex2(string specificValue)//Job Difficulty
...