Home > OS >  Convert a Stream into json value c#
Convert a Stream into json value c#

Time:01-11

I have below stream which I get from this line where req1 is of HttpResponseMessage type and responseMessage is of type Stream. How can I convert this Stream into a json Object. My end goal is to extract values from the specific keys in this json.

var responseMessage = await req1.Content.ReadAsStreamAsync();

CodePudding user response:

Above answer has a class defined. I didnt want to define different class as my model is dynamic. I found this solution , which worked well and got me the desired result

var serializer = new JsonSerializer();

            using (var sr = new StreamReader(responseMessage))
            using (var jsonTextReader = new JsonTextReader(sr))
            {
                var jsObj= serializer.Deserialize(jsonTextReader);
            }

CodePudding user response:

try it

// read file into a string and deserialize JSON to a type
Movie movie1 = JsonConvert.DeserializeObject<Movie>(File.ReadAllText(@"c:\movie.json"));

// deserialize JSON directly from a file
using (StreamReader file = File.OpenText(@"c:\movie.json"))
{
    JsonSerializer serializer = new JsonSerializer();
    Movie movie2 = (Movie)serializer.Deserialize(file, typeof(Movie));
}
  •  Tags:  
  • Related