Purpose
This purpose of this brief tutorial is to show how to parse form submission data, when you need to do it manually such as when there are no pre-existing models for a form where you could usually use [FromBody] for .Net to automatically map the data to the model class. This example also shows how to use a List of List.
Ready? Here we go!
/* Form Data name/value Model */
public class FormGenericModel {
public string ElementName { get; set; } = string.Empty;
public string ElementValue { get; set; } = string.Empty;
}
using System.Collections.Generic;
using System.Text.Json;
using System.Text.RegularExpressions;
/* Handles an array of objects [{"a":"b"},{...}] */
public List<List<FormGenericModel>> extractArrayJsonPairs(string json) {
List<List<FormGenericModel>> configData = new List<List<FormGenericModel>>();
using (JsonDocument jdoc = JsonDocument.Parse(json)) {
foreach (JsonElement je in jdoc.RootElement.EnumerateArray()) {
List<FormGenericModel> formData = new List<FormGenericModel>();
formData = extractJsonPairsOfRegEx(je.ToString());
configData.Add(formData);
}
}
return configData;
}
/* Handles an object that is not in an array, such as a submitted form {"a":"b", "c":"d"...} */
public List<FormGenericModel> extractJsonPairs(string json) {
List<FormGenericModel> formData = new List<FormGenericModel>();
using (JsonDocument jdoc = JsonDocument.Parse(json)) {
foreach (JsonProperty kv in jdoc.RootElement.EnumerateObject()) {
var key = kv.Name.ToString();
var value = kv.Value.ToString();
formData.Add(new FormGenericModel() { ElementName = key, ElementValue = value });
}
}
return formData;
}
/* Similiar to extractJsonPairs() but decodes regex data in json, such as may be present in a database; turning "%5E%58a-zA-Z0-9%5D*%24" into "^[a-zA-Z0-9]*$" */
public List<FormGenericModel> extractJsonPairsOfRegEx(string json) {
List<FormGenericModel> formData = new List<FormGenericModel>();
using (JsonDocument jdoc = JsonDocument.Parse(json)) {
foreach (JsonProperty kv in jdoc.RootElement.EnumerateObject()) {
var key = kv.Name.ToString();
var value = kv.Value.ToString();
if (value.Trim().Length > 0 && value.IndexOf("%") > -1) { value = Uri.UnescapeDataString(value); }
formData.Add(new FormGenericModel() { ElementName = key, ElementValue = value });
}
}
return formData;
}