I am hitting a 3rd party api and getting a plain text response in the body with the following format:
item[0].Name = name
item[0].Type = type
item[1].Name etc...
Is there a simple way of taking this and mapping it to an object or JSON in c#?
I've tried manipulating the string to replace "\n" with "," and "=" with ":" and serializing it as a JSON object but didn't get anywhere with it. I also tried splitting the string and creating objects from it that way which worked but I need to hit a lot of endpoints from this api with varying results and it's not a very clean solution.
Edit
After reading the response content as a string the exact format of the response is
item[0].Name=name\r\nitem[0].Type=type\r\nitem[1].Name=name\r\nitem[1].Type=type
Any help is very appreciated!
Try this, it was tested in Visual Studio
static void Main()
{
var t = @"item[0].Name = name0
item[0].Type = type0
item[1].Name = name1
item[1].Type = type1";
var ta = t.Split("\r\n");
List<NameType> list = new List<NameType>();
for (var i = 0; i < ta.Length; i += 2)
{
var itemNameArr = ta[i].Split("=");
var itemTypeArr = ta[i + 1].Split("=");
if( itemNameArr[0].Substring(0,itemNameArr[0].IndexOf("."))
!= itemTypeArr[0].Substring(0,itemNameArr[0].IndexOf("."))) return //error ;
var itemName = itemNameArr[1].Replace("\r", string.Empty).Replace("\n", string.Empty);
var itemType= itemTypeArr[1].Replace("\r", string.Empty).Replace("\n", string.Empty);
list.Add(new NameType { Name = itemName, Type = itemType });
}
var json = JsonSerializer.Serialize(list);
}
public class NameType
{
public string Name { get; set; }
public string Type { get; set; }
}
json
[
{
"Name": " name0",
"Type": " type0"
},
{
"Name": " name1",
"Type": " type1"
}
]