Send JSON via POST in C# and Receive the JSON returned?

前端 未结 4 910
耶瑟儿~
耶瑟儿~ 2020-12-02 09:59

This is my first time ever using JSON as well as System.Net and the WebRequest in any of my applications. My application is supposed to send a JSON

4条回答
  •  余生分开走
    2020-12-02 11:00

    You can build your HttpContent using the combination of JObject to avoid and JProperty and then call ToString() on it when building the StringContent:

            /*{
              "agent": {                             
                "name": "Agent Name",                
                "version": 1                                                          
              },
              "username": "Username",                                   
              "password": "User Password",
              "token": "xxxxxx"
            }*/
    
            JObject payLoad = new JObject(
                new JProperty("agent", 
                    new JObject(
                        new JProperty("name", "Agent Name"),
                        new JProperty("version", 1)
                        ),
                    new JProperty("username", "Username"),
                    new JProperty("password", "User Password"),
                    new JProperty("token", "xxxxxx")    
                    )
                );
    
            using (HttpClient client = new HttpClient())
            {
                var httpContent = new StringContent(payLoad.ToString(), Encoding.UTF8, "application/json");
    
                using (HttpResponseMessage response = await client.PostAsync(requestUri, httpContent))
                {
                    response.EnsureSuccessStatusCode();
                    string responseBody = await response.Content.ReadAsStringAsync();
                    return JObject.Parse(responseBody);
                }
            }
    

提交回复
热议问题