简体   繁体   English

将文本/普通多行 key=value http 响应映射到 json 和/或 c# 对象

[英]Map text/plain multiline key=value http response to json and or c# object

I am hitting a 3rd party api and getting a plain text response in the body with the following format:我正在访问第 3 方 api 并在正文中获得以下格式的纯文本响应:

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#?有没有一种简单的方法可以将其映射到 c# 中的对象或 JSON?

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.我尝试操作字符串以将 "\\n" 替换为 "," 并将 "=" 替换为 ":" 并将其序列化为 JSON 对象,但没有得到任何结果。 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.我还尝试以这种方式拆分字符串并从中创建对象,但我需要从这个 api 中访问很多端点并产生不同的结果,这不是一个非常干净的解决方案。

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将响应内容作为字符串读取后,响应的确切格式为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试试这个,它在 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 json

[
  {
    "Name": " name0",
    "Type": " type0"
  },
  {
    "Name": " name1",
    "Type": " type1"
  }
]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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