I am building a C# Web API and once you POST data to the endpoint, it will generate a HTML email with the values posted.
Unfortunately I'm stuck on how to parse and loop over the JSON array that contains key/value pairs and ultimately generate a HTML table row as a result.
Sample JSON data im testing with:
{
"Submitter":[
{
"Obj1":[
"test",
"test2"
]
},
{
"Obj2":[
"test3",
"test4"
]
}
]
}
Code:
public class TestingController : ControllerBase
{
public object Submitter { get; set; }
public string POST([FromBody] TestingController data)
{
var json = JsonConvert.SerializeObject(data.Submitter);
var jsonObjects = JObject.Parse(json);
var submitData = jsonObjects["Submitter"];
string body = "";
foreach (var item in submitData)
{
body += $"{item["Obj1"]}"; // Not working
}
return body;
}
}
Desired html render once being able to successfully loop the array:
body += $"<tr><td>{item["Obj1"]}</td><td>{item["Obj2"]}</td></tr>"
EDIT
I still struggling but slowly getting one step closer:
public class TestingController : ControllerBase
{
public List<SubmitterObjects> Submitter { get; set; }
public class SubmitterObjects
{
public List<string> Obj1 { get; set; }
public List<string> Obj2 { get; set; }
}
public string POST([FromBody] TestingController data)
{
var json = JsonConvert.SerializeObject(data);
dynamic myDeserializedClass = JsonConvert.DeserializeObject(json);
string body = "";
foreach (var item in myDeserializedClass.Submitter)
{
body += $"<tr><td>{item.Obj1}</td><td>{item.Obj2}</td></tr>";
}
return body;
}
}
Result (weird):
<tr><td>[
"test",
"test2"
]</td><td></td></tr><tr><td></td><td>[
"test3",
"test4"
]</td></tr>
Desired HTML table result:
| Object 1 | Object 2 |
|----------|----------|
| Test | Test 3 |
| Test 2 | Test 4 |
Obj1andObj2should be represented in the resulting HTML. Could you please add the desired HTML output. Also consider using a StringBuilder instead of concatenatingbody += ...bodywill contain a table which is why im trying to append Obj1 & Obj2 to it. Although what im really trying to achieve here is being able to successfully loop over the JSON array, the HTML generation part of it is easy and I will look into String Builderitemby JArray.ChildrenTokens.