-4

I have a C# application getting a string from an HTTP listener. The data is sent to my application in the JSON format, and I am trying to get the specific values.

Right now, I read the data sent to me using:

            HttpListenerContext context = listener.GetContext();
            var request = context.Request;
            string message;
            using (var reader = new StreamReader(request.InputStream,
                                                 request.ContentEncoding))
            {
                message = reader.ReadToEnd();
            }

The string message = { "message": "I've been shot!", "phoneNumber": "12345?", "position": "???", "anon": "???", "job": "ambulance" }

How would I go about getting these specific values and setting a string equal to the message, phonenumber, position, etc. Instead of just using the reader.ReadToEnd()

Thanks!

Brian S
  • 385
  • 3
  • 16

1 Answers1

-1

Using Netwonsoft.Json, you can create an anonymous type to use as a template, then use the type to create an object with friendly property names. You even get intellisense!

Example of parsing your example object:

public static void Main()
{

    string input = @"{ ""message"": ""I've been shot!"", ""phoneNumber"": ""12345?"", ""position"": ""???"", ""anon"": ""???"", ""job"": ""ambulance"" }";
    var objectTemplate = new
    {
        message = "", 
        phoneNumber = "", 
        position = "", 
        anon = "", 
        job = ""
    };

    var deserialized = JsonConvert.DeserializeAnonymousType(input, objectTemplate);

    Console.WriteLine(deserialized.message);
    Console.WriteLine(deserialized.phoneNumber);
    Console.WriteLine(deserialized.position);

}

Output:

I've been shot!
12345?
???

Code on DotNetFiddle

John Wu
  • 50,556
  • 8
  • 44
  • 80