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

前端 未结 4 885
耶瑟儿~
耶瑟儿~ 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 10:48

    Using the JSON.NET NuGet package and anonymous types, you can simplify what the other posters are suggesting:

    // ...
    
    string payload = JsonConvert.SerializeObject(new
    {
        agent = new
        {
            name    = "Agent Name",
            version = 1,
        },
    
        username = "username",
        password = "password",
        token    = "xxxxx",
    });
    
    var client = new HttpClient();
    var content = new StringContent(payload, Encoding.UTF8, "application/json");
    
    HttpResponseMessage response = await client.PostAsync(uri, content);
    
    // ...
    
    0 讨论(0)
  • 2020-12-02 10:50

    You can also use the PostAsJsonAsync() method available in HttpClient()

       var requestObj= JsonConvert.SerializeObject(obj);
       HttpResponseMessage response = await    client.PostAsJsonAsync($"endpoint",requestObj).ConfigureAwait(false);

    0 讨论(0)
  • 2020-12-02 10:58

    I found myself using the HttpClient library to query RESTful APIs as the code is very straightforward and fully async'ed.

    (Edit: Adding JSON from question for clarity)

    {
      "agent": {                             
        "name": "Agent Name",                
        "version": 1                                                          
      },
      "username": "Username",                                   
      "password": "User Password",
      "token": "xxxxxx"
    }
    

    With two classes representing the JSON-Structure you posted that may look like this:

    public class Credentials
    {
        [JsonProperty("agent")]
        public Agent Agent { get; set; }
    
        [JsonProperty("username")]
        public string Username { get; set; }
    
        [JsonProperty("password")]
        public string Password { get; set; }
    
        [JsonProperty("token")]
        public string Token { get; set; }
    }
    
    public class Agent
    {
        [JsonProperty("name")]
        public string Name { get; set; }
    
        [JsonProperty("version")]
        public int Version { get; set; }
    }
    

    you could have a method like this, which would do your POST request:

    var payload = new Credentials { 
        Agent = new Agent { 
            Name = "Agent Name",
            Version = 1 
        },
        Username = "Username",
        Password = "User Password",
        Token = "xxxxx"
    };
    
    // Serialize our concrete class into a JSON String
    var stringPayload = await Task.Run(() => JsonConvert.SerializeObject(payload));
    
    // Wrap our JSON inside a StringContent which then can be used by the HttpClient class
    var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/json");
    
    using (var httpClient = new HttpClient()) {
    
        // Do the actual request and await the response
        var httpResponse = await httpClient.PostAsync("http://localhost/api/path", httpContent);
    
        // If the response contains content we want to read it!
        if (httpResponse.Content != null) {
            var responseContent = await httpResponse.Content.ReadAsStringAsync();
    
            // From here on you could deserialize the ResponseContent back again to a concrete C# type using Json.Net
        }
    }
    
    0 讨论(0)
  • 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);
                }
            }
    
    0 讨论(0)
提交回复
热议问题