从字符串内部提取键值对

本文关键字:键值对 提取 内部 字符串 | 更新日期: 2023-09-27 18:25:34

我有以下字符串:

string myString = "{'gridObject':'[1,2,3,4],[5,6,7,8]'}";

我如何将其处理成一个对象,以便我可以这样做:

charts[0]     //=> [1,2,3,4]
charts[0][1]  //=> 2

如果我能把它转换成这个对象,那就更好了:

public class gridObject {
    public int datarow   {get; set;}
    public int datacol   {get; set;}
    public int datasizex {get; set;}
    public int datasizey {get; set;}
}

从字符串内部提取键值对

这就是我要做的。

首先创建你的类,

public class GridObject
{
    public int datarow { get; set; }
    public int datacol { get; set; }
    public int datasizex { get; set; }
    public int datasizey { get; set; }
}
public class GridObjectCollection
{
    public GridObject[] GridObjects { get; set; }
}

然后,要查看您需要什么JSON,请将其序列化一次:(JsonConvert是JSON.NET的一部分,您可以使用NuGet获得它)

GridObjectCollection gridObjects = new GridObjectCollection();
gridObjects.GridObjects = new GridObject[]
{
    new GridObject() { datacol = 1, datarow = 2, datasizex = 3, datasizey = 4 },
    new GridObject() { datacol = 5, datarow = 6, datasizex = 7, datasizey = 8 }
};
Console.WriteLine
(
    JsonConvert.SerializeObject
    (
        gridObjects,
        new JsonSerializerSettings() { Formatting = Formatting.Indented }
    )
);

在这里,您可以看到在反序列化时将生成这些类的有效JSON内容如下:

{
  "GridObjects": [
    {
      "datarow": 2,
      "datacol": 1,
      "datasizex": 3,
      "datasizey": 4
    },
    {
      "datarow": 6,
      "datacol": 5,
      "datasizex": 7,
      "datasizey": 8
    }
  ]
}

然后,只需尝试反序列化以确保:

var f = JsonConvert.DeserializeObject<GridObjectCollection>
(
    "{'GridObjects':[{'datarow':2,'datacol':1,'datasizex':3,'datasizey':4},{'datarow':6,'datacol':5,'datasizex':7,'datasizey':8}]}"
);

这里有一种方法:

public static gridObject[] Parse(string str)
{
    int first = str.IndexOf("[");
    int last = str.LastIndexOf("]");
    str = str.Substring(first, last - first + 1);
    string[] big_parts = str.Split(new string[] {"[", "],[", "]"} , StringSplitOptions.RemoveEmptyEntries);

    return big_parts.Select(x =>
    {
        string[] small_parts = x.Split(',');
        return new gridObject()
        {
            datarow = Convert.ToInt32(small_parts[0]),
            datacol = Convert.ToInt32(small_parts[1]),
            datasizex = Convert.ToInt32(small_parts[2]),
            datasizey = Convert.ToInt32(small_parts[3]),
        };
    }).ToArray();
}

它首先搜索第一个[和最后一个],并修剪[之前和]之后的任何内容。

然后,它基于[],[]来分割字符串。

这将为您的示例提供1,2,3,45,6,7,8

然后,对于其中的每一个,我们基于,进行拆分,并将结果转换为gridObject对象。

完成自定义解析:

public class GridObject
{
    public int datarow { get; set; }
    public int datacol { get; set; }
    public int datasizex { get; set; }
    public int datasizey { get; set; }
}
/// <summary>
/// MySuperObject class which holds a reference to inner array of integers
/// </summary>
public class MySuperObject
{
    public List<int> Items { get; set; } // Inner array of list of integers
    public MySuperObject()
    {
        Items = new List<int>();
    }
    public override string ToString()
    {
        // Need to override ToString to return something like "[1,2,3,4]"
        var result = "";
        foreach (var item in Items)
        {
            if (result.Length > 0)
                result += ",";
            result += item.ToString();
        }
        return string.Format("[{0}]", result);
    }
    /// <summary>
    /// Function to generate GridObject from existing set of integers
    /// </summary>
    public GridObject GetGridObject()
    {
        var result = new GridObject();
        if (Items.Count >= 1) result.datarow = Items[0];
        if (Items.Count >= 2) result.datacol = Items[1];
        if (Items.Count >= 3) result.datasizex = Items[2];
        if (Items.Count >= 4) result.datasizey = Items[3];
        return result;
    }
}
// Parse functions
public List<MySuperObject> Parse(string value)
{
    if (string.IsNullOrEmpty(value))
        throw new ArgumentException("value cannot be null or empty!", "value");
    var result = new List<MySuperObject>();
    // First get the indexes of first [ and last ]
    var idxStart = value.IndexOf("[");
    var idxEnd = value.LastIndexOf("]");
    // Check validity
    if (idxStart < 0 || idxEnd < 0 || idxEnd <= idxStart)
        return result; // Return empty list
    value = value.Substring(idxStart, idxEnd - idxStart + 1).Trim();
    // Split by [] after replacing spaces with empty strings (and removing first and last [ and ])
    var arr = value.Replace(" ", "").Trim('[',']').Split(new[] { "],[" }, StringSplitOptions.RemoveEmptyEntries);
    foreach (var str in arr)
    {
        // Construct list of integers with a help of LINQ
        var nums = str.Split(',').Select(t => Convert.ToInt32(t)).ToList();
        // Create and add MySuperObject to existing list which will be returned
        result.Add(new MySuperObject
        {
            Items = new List<int>(nums),
        });
    }
    return result;
}

下面是这种解析的用法:

var myString = "{'gridObject':'[1,2,3,4],[5,6,7,8]'}";
var value = Parse(myString);
// Get all grid objects
var allGridObjects = value.Select(t => t.GetGridObject()).ToList();

当然,这可能需要更多的错误检查,但基本上,这个MySuperObject用于使用您想要的任何数量的整数,同时为您提供一个"GetGridObject"的辅助方法,用数字数组中的适当数字填充网格对象。