JSON को CST के माध्यम से C # में भेजें और JSON प्राप्त करें?


86

यह मेरा पहला कभी JSON का उपयोग कर के रूप में भी है System.Netऔर WebRequestमेरी अनुप्रयोगों में से किसी में। मेरा आवेदन एक JSON पेलोड भेजने के लिए माना जाता है, एक प्रमाणीकरण सर्वर के नीचे एक के समान:

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

इस पेलोड को बनाने के लिए, मैंने JSON.NETलाइब्रेरी का उपयोग किया । मैं इस डेटा को प्रमाणीकरण सर्वर पर कैसे भेजूंगा और इसकी JSON प्रतिक्रिया वापस पाऊंगा? यहाँ मैंने कुछ उदाहरणों में देखा है, लेकिन कोई JSON सामग्री नहीं:

var http = (HttpWebRequest)WebRequest.Create(new Uri(baseUrl));
http.Accept = "application/json";
http.ContentType = "application/json";
http.Method = "POST";

string parsedContent = "Parsed JSON Content needs to go here";
ASCIIEncoding encoding = new ASCIIEncoding();
Byte[] bytes = encoding.GetBytes(parsedContent);

Stream newStream = http.GetRequestStream();
newStream.Write(bytes, 0, bytes.Length);
newStream.Close();

var response = http.GetResponse();

var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();

हालाँकि, यह उन अन्य भाषाओं का उपयोग करने के लिए बहुत अधिक कोड है जो मैंने पूर्व में उपयोग की गई भाषाओं के लिए उपयोग किए हैं। क्या मैं यह सही ढंग से कर रहा हूं? और मुझे JSON की प्रतिक्रिया वापस कैसे मिलेगी ताकि मैं इसे पार्स कर सकूं?

धन्यवाद, अभिजात वर्ग।

अपडेटेड कोड

// Send the POST Request to the Authentication Server
// Error Here
string json = await Task.Run(() => JsonConvert.SerializeObject(createLoginPayload(usernameTextBox.Text, password)));
var httpContent = new StringContent(json, Encoding.UTF8, "application/json");
using (var httpClient = new HttpClient())
{
    // Error here
    var httpResponse = await httpClient.PostAsync("URL HERE", httpContent);
    if (httpResponse.Content != null)
    {
        // Error Here
        var responseContent = await httpResponse.Content.ReadAsStringAsync();
    }
}

2
आप कोशिश कर सकते हैं WebClient.UploadString(JsonConvert.SerializeObjectobj(yourobj))याHttpClient.PostAsJsonAsync
LB

जवाबों:


129

मैंने RESTful API को क्वेरी करने के लिए HttpClient लाइब्रेरी का उपयोग करके खुद को पाया क्योंकि कोड बहुत सीधा और पूरी तरह से async'ed है।

(संपादित करें: स्पष्टता के लिए सवाल से JSON जोड़ना)

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

JSON-संरचना का प्रतिनिधित्व करने वाले दो वर्गों के साथ, जो आपने इस तरह दिख सकते हैं:

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; }
}

आपके पास इस तरह की एक विधि हो सकती है, जो आपके POST अनुरोध को करेगी:

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
    }
}

5
एकदम सही है, लेकिन इंतजार क्या है। टास्क () (?)
हंटर मिशेल

21
आप तुल्यकालिक सीपीयू बाध्य तरीकों पर टास्क का उपयोग नहीं करना चाहिए क्योंकि आप बिना किसी लाभ के एक नया धागा निकाल रहे हैं!
स्टीफन फोस्टर

2
आपको JsonPropertyहर प्रॉपर्टी के लिए टाइप करने की जरूरत नहीं है । बस Json.Net का उपयोग CamelCasePropertyNamesContractResolver में बनाया गया है या क्रमांकन प्रक्रिया को अनुकूलित करने के लिए एक कस्टमNamingStrategy
सीफिश

6
साइड नोट: एक के usingसाथ प्रयोग नहीं करते HttpClient। देखें: aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong
मैक्सशूट

4
System.Net.Http.Formatting के साथ आपके पास एक्सटेंशन तरीके परिभाषित हैं: "httpClient.PostAsJsonAsync (" एपीआई / v1 / डोमेन ", csObjRequest) का
इंतजार करें

13

JSON.NET NuGet पैकेज और अनाम प्रकारों का उपयोग करके, आप सरल कर सकते हैं कि अन्य पोस्टर क्या सुझाव दे रहे हैं:

// ...

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);

// ...

6

आप से बचने HttpContentके संयोजन का उपयोग करके अपने निर्माण कर सकते हैं और फिर निर्माण करते समय उस पर कॉल करें :JObjectJPropertyToString()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);
            }
        }

आप Exception while executing function. Newtonsoft.Json: Can not add Newtonsoft.Json.Linq.JProperty to Newtonsoft.Json.Linq.JArrayत्रुटियों से कैसे बचते हैं?
जरी तुर्किया

1
एक HttpClient उदाहरण निर्माण का उपयोग करने के साथ बनाने के लिए नहीं माना जाता है। उदाहरण एक बार बनाया जाना चाहिए और पूरे अनुप्रयोग में उपयोग किया जाना चाहिए। ऐसा इसलिए है क्योंकि यह अपने स्वयं के कनेक्शन पूल का उपयोग करता है। आपका कोड अधिकांशतः SocketException को फेंक देता है। docs.microsoft.com/en-us/dotnet/api/…
हरुन दिलुका हेशान

2

आप HttpClient () में उपलब्ध PostAsJsonAsync () विधि का भी उपयोग कर सकते हैं

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


1
क्या आप कृपया स्पष्टीकरण जोड़ सकते हैं कि आपका कोड क्या करता है और यह समस्या को कैसे हल करता है?
नीलांबर शर्मा

आप SerializeObject () का उपयोग करके जो भी वस्तु पोस्ट करना चाहते हैं और ले सकते हैं; var obj= new Credentials { Agent = new Agent { Name = "Agent Name", Version = 1 }, Username = "Username", Password = "User Password", Token = "xxxxx" }; और फिर इसे HTTPContent में बदलने के बिना, आप समापन बिंदु URL और परिवर्तित JSON ऑब्जेक्ट स्वयं PostAsJsonAsync () का उपयोग कर सकते हैं।
रुक्शाला वेरासिंघे
हमारी साइट का प्रयोग करके, आप स्वीकार करते हैं कि आपने हमारी Cookie Policy और निजता नीति को पढ़ और समझा लिया है।
Licensed under cc by-sa 3.0 with attribution required.