2017-01-23 112 views
0

我必須調用一個需要3級json請求的api。Post 3級複雜的C#對象posstasjsonaynch

class foo { public List<StudentList> students { get; set; } } 

class StudentList 
{ 
    public string studentid { get; set; } 

    public string researchId { get; set; } 

    public List<courses> courseList { get; set; } 
    public List<examsschedule> exams { get; set } 
} 

class courses { 
    public string courseId { get; set; } 
    public string courseName { get; set; } 
    public string professsorName { get; set; } 
} 

class exams 
{ 
    /****/ 
} 

我必須發佈這個作爲JSON到API。 postasjsonasynch

當我發送「foo」類的對象時,api拒絕,因爲它不是json格式。

var payload = fooObject 

/*object of foo*/ 
var httpContent = new StringContent(payload, Encoding.UTF8,"application/json"); 

我使用的Web API的postasjsonaynch

[jsonproperty]這是隻用於捕捉響應或還建立請求中使用?

回答

0

這裏是解決方案,

 static void Main(string[] args) 
     { 
      var url = "http://localhost:64743/"; 
      var client = new HttpClient(); 
      client.BaseAddress = new Uri(url); 

      //Post  
       var students = new List<StudentList> 
       { 
       new StudentList { researchid="1234", studentid="5689", 
        courses = new List<Course> 
        { 
        new Course { courseName="os", professorName="donchi lee"   }, 
         new Course { courseName="database", professorName="jie,joe" } 
          }, 
             exams=new List<Exam> { } 
           } 
           }; 

          var response = client.PostAsJsonAsync("api/Student", students).ConfigureAwait(false).Result; 
         if (response.IsSuccessStatusCode) 
           { 
           Console.WriteLine(response.StatusCode); 
            } 
             }