C# 从字符串内部提取键值对
我有以下字符串:C# 从字符串内部提取键值对,c#,asp.net-mvc,string,keyvaluepair,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
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 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,4
和5,6,7,8
然后,我们根据
,
对它们中的每一个进行拆分,并将结果转换为gridObject
对象。以下是一种方法:
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,4
和5,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; }
}
public class GridObjectCollection
{
public GridObject[] GridObjects { get; set; }
}
然后,为了查看您需要什么JSON,将其序列化一次:(JsonConvert是的一部分,您可以使用NuGet获得它)
在这里,您可以看到反序列化时将生成这些类的有效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}]}"
);
var f=JsonConvert.DeserializeObject
(
“{'GridObjects':[{'datarow':2,'datacol':1,'datasizex':3,'datasizey':4},{'datarow':6,'datacol':5,'datasizex':7,'datasizey':8}”
);
这就是我要做的
首先创建您的类
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是的一部分,您可以使用NuGet获得它)
在这里,您可以看到反序列化时将生成这些类的有效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}]}"
);
var f=JsonConvert.DeserializeObject
(
“{'GridObjects':[{'datarow':2,'datacol':1,'datasizex':3,'datasizey':4},{'datarow':6,'datacol':5,'datasizex':7,'datasizey':8}”
);
使用自定义解析完成:
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;
}
当然,这可能需要更多的错误检查,但基本上,这个MySuperObject用于使用您想要的任意数量的整数,同时为您提供“GetGridObject”的帮助方法,用数字数组中的适当数字填充网格对象。使用自定义解析完成:
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;
}
当然,这可能需要更多的错误检查,但基本上,这个MySuperObject用于使用您想要的任意数量的整数,同时为您提供“GetGridObject”的帮助方法用数字数组中的适当数字填充网格对象。这里的最大问题是,在输入的两个级别上都有一个明显的分隔符(逗号)——分隔数字和分隔数字集。您对这些数据的格式有多大的控制权?你能换一下吗?你试过什么?外部对象看起来像JSON,因此
gridObject
的值可以单独解析。ChrisF:我完全可以控制格式。我可以更改分隔符和其他一切。您可以使用JSON解析库:一次用于myString
字符串本身,然后再次用于字符串,方法是用额外的方括号将[1,2,3,4],[5,6,7,8]
包装起来,以确保它是格式正确的JSON字符串(2D数组)。请参阅“我完全控制格式”-使其与数组和所有内容完全有效,那么解析就很简单了。这里的大问题是在输入的两个级别上有一个明显的分隔符(逗号)——分隔数字和分隔数字集。您对这些数据的格式有多大的控制权?你能换一下吗?你试过什么?外部对象看起来像JSON,因此gridObject
的值可以单独解析。ChrisF:我完全可以控制格式。我可以更改分隔符和其他一切。您可以使用JSON解析库:一次用于myString
字符串本身,然后再次用于字符串,方法是用额外的方括号将[1,2,3,4],[5,6,7,8]
包装起来,以确保它是格式正确的JSON字符串(2D数组)。请参阅“我完全控制格式”-使用数组和所有内容使其完全有效,那么解析就很简单了。谢谢,我将尝试一下。我是新来C#的,所以我真的很感谢你的解释。谢谢你,我来试试。我是C#的新手,所以我非常感谢你的解释。谢谢!不相关的问题:是否有一个“沙箱”环境可以用来快速测试类似的东西,而不需要在我的项目中实际实现它并运行项目?我正在寻找类似于浏览器javascript控制台的东西,您可以在其中键入语句并查看它们是如何计算的。我使用Visual Studio 2015。+1到@LucMorin。您还可以将json复制到剪贴板,并在Visual Studio中的类窗口中,编辑->粘贴特殊->粘贴json为Classes@OguzOzgul啊。。。俏皮:)@LucMorin如果我之前知道,它就在那里,自VS 2012发布以来就隐藏在编辑菜单中:)谢谢!不相关的问题:是否有一个“沙箱”环境可以用来快速测试类似的东西,而不需要在我的项目中实际实现它并运行项目?我正在寻找类似于浏览器javascript控制台的东西,您可以在其中键入语句并查看它们是如何计算的。我使用Visual Studio 2015。+1到@LucMorin。您还可以将json复制到剪贴板,并在Visual Studio中的类窗口中,编辑->粘贴特殊->粘贴json为Classes@OguzOzgul啊。。。妮蒂:)@LucMorin如果我早知道它就在那里,那我就可以省下几个小时了,hidde