2017-01-23 75 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); 
            } 
             }