2

I'm trying to read values of a raw JSON POST request, and convert only the passed in field (key) names to an object.

If I post a JSON string such as:

{ 
     "FirstName": "Test",
     "LastName": "User",
     "MiddleInitials": null
}

And then I convert the JSON string to an object, after reading the input stream from the request body:

// Read the InputStream
StreamReader reader = new StreamReader(Request.Body);
reader.BaseStream.Position = 0;
string jsonText = reader.ReadToEnd();

// Deserialize to object and read property names
object jsonObject = JsonConvert.DeserializeObject(jsonText);

Then when I inspect the object, I see the following: enter image description here How do I just get the key values (FirstName, LastName, MiddleInitials)?

kyle_13
  • 1,173
  • 6
  • 25
  • 47
  • 2
    Create a class with those three properties, then deserialize an instance of that class. –  May 18 '18 at 15:36
  • Related: [How can I get a list of keys from Json.NET?](https://stackoverflow.com/questions/6522358/how-can-i-get-a-list-of-keys-from-json-net) – ProgrammingLlama May 18 '18 at 15:37
  • Hi @Amy to be clear (sorry if I wasn't before), the scenario is that I am just trying to read the key values that come in, as they may or may not be correct (match the class). For example, if someone were to pass in "FirstNaem" instead of "FirstName", that value would just be ignored when mapping to the class. – kyle_13 May 18 '18 at 16:03
  • @kyle_13 That's an important detail. I recommend editing that into your question. –  May 18 '18 at 16:18
  • 1
    @kyle_13 Generally though, when some JSON doesn't match an expected model, that should result in a 400 BAD REQUEST error. –  May 18 '18 at 16:22

1 Answers1

2

NewtonSoft JSON libraries allow you to deserialize JSON into a specific type using generics, check out this documentation. It'll also throw an error if the JSON string doesn't match up with the object your attempting to deserialize into.

Another option that I occasionally do is to deserialize a JSON string into a dynamic instead of an object. It saves you from having to create a type for every single response that you're expecting. Check out this question/answer for an example.

JosephRT
  • 545
  • 4
  • 19