从字符串内部提取键值对

时间:2015-12-02 22:35:59

标签: c# asp.net-mvc string keyvaluepair

我有以下字符串:

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;}

}

3 个答案:

答案 0 :(得分:3)

这就是我要做的。

首先创建课程,

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,请将其序列化一次:( JsonConvert是Json.NET的一部分,您可以使用NuGet获取它)

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

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

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

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

def seasons(row):
    return row['Year'] % 2011 * 4 + row['Season']

df.reset_index(inplace=True)
df['seasons'] = df.apply(seasons, axis=1)
df.set_index(['Season', 'Year', 'Location'], inplace=True)

答案 1 :(得分:1)

这是一种方法:

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对象。

答案 2 :(得分:0)

完成自定义解析:

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”的辅助方法来用适当的方式填充你的网格对象数字数组中的数字。