简体   繁体   中英

Need to parse a JSON coming in via a Post request

I am trying to parse a JSON received in a Post request.

The JSON is as follows. It has to be agnostic as to how many records there are or what the fields are called. But the contact variable is always null when I send it via Postman. Is there something wrong with the class I throw it in to?

{
  "Fields": 
  {
   "first":"fn",
   "last":"ln",
   ...
  }
}
    public class FieldsValues
    {
      List<KeyValuePair<string, string>> Fields =  new List<KeyValuePair<string, string>>() { };
    }

    public void Post([FromBody]FieldsValues Fields)
    {

       ...
    }

I want to send the JSON into a Dictionary object but the value coming in is always null.

Your Json is not an array. You need square brackets to build an array. Besides this the KeyValuePair has members named "Key" and "Value". To match the List<KeyValuePair<string, string>> you'll need to input something like this:

{
  "Fields": 
  [{
   "Key":"first",
   "Value":"fn"
  }]
}

If you can't change the JSON structure yourself and the structure is really unknown to you, I would go for a method that accepts raw strings and parse that string with Newtonsoft to a dynamic object. Eg this code could accept your JSON:

        public void Post()
        {
            string text = "";
            using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
                text = reader.ReadToEnd();

            dynamic dynObj = JObject.Parse(text);

            var firstValue = dynObj.Fields.first.Value;
            ...
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM