Convert JSON response stream to string

I am trying to do a POST and then read the JSON response in a string.

I believe my problem is that I need to pass my own object to the DataContractJsonSerializer, but I am wondering if there is any way to just get the response into an associative array or some kind of key / value format.

My JSON has the following format: {"license": "AAAA-AAAA-AAAA-AAAA"}, and my code looks like this:

using (Stream response = HttpCommands.GetResponseStream(URL, FormatRegistrationPost(name, email))) { string output = new StreamReader(response).ReadToEnd(); response.Close(); DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(string)); MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(output)); string results = json.ReadObject(ms) as string; licenseKey = (string) results.GetType().GetProperty("license").GetValue(results, null); } 
+4
source share
2 answers

I highly recommend a peek at Newtonsoft.Json:

http://james.newtonking.com/pages/json-net.aspx

NuGet: https://www.nuget.org/packages/newtonsoft.json/

After adding a link to your project, you simply include using at the top of the file:

 using Newtonsoft.Json.Linq; 

And then as part of your method, you can use:

 var request= (HttpWebRequest)WebRequest.Create("www.example.com/ex.json"); var response = (HttpWebResponse)request.GetResponse(); var rawJson = new StreamReader(response.GetResponseStream()).ReadToEnd(); var json = JObject.Parse(rawJson); //Turns your raw string into a key value lookup string license_value = json["license"].ToObject<string>(); 
+17
source

you can do something like this with a dictionary

 Dictionary<string, string> values = JsonConvert.DeserializeObject<Dictionary<string, string>>(json); 

or something like this if you already know your object

 var yourobject = JsonConvert.DeserializeObject<YourObject>(json); 

with this tool

http://james.newtonking.com/projects/json/help/

link here Using JsonConvert.DeserializeObject to deserialize Json into a C # POCO class

+1
source

Source: https://habr.com/ru/post/1441704/


All Articles