[英]Convert the string containing array and dict into the list and vice versa in c#
How can we convert the following string into a list and vice versa in c#?我们如何在 c# 中将以下字符串转换为列表,反之亦然?
String1: "['hello', 'world', 100, 12.59, [1, '2', ['3', 4, {'key': 'value'}]]]"
Expected List1: ['hello', 'world', 100, 12.59, [1, '2', ['3', 4, {'key': 'value'}]]]
Expected results:预期成绩:
Console.WriteLine(List1[0]) //Output: 'hello'
Console.WriteLine(List1[4][2][1]) //Output: 4
Console.WriteLine(List1[4][2][2]['key']) //Output: 'value'
Note:笔记:
In python , we have an eval(expression) method to convert the string into a list .在python 中,我们有一个eval(expression)方法可以将字符串转换为列表。
we have a repr(obj) method to convert the list back into a string .我们有一个repr(obj)方法将列表转换回字符串。
Please refer to the below sample code using python methods.请使用python方法参考以下示例代码。 I require similar methods in c#.
我需要在 c# 中使用类似的方法。
>>> str1="['hello', 'world', 100, 12.59, [1, '2', ['3', 4, {'key': 'value'}]]]"
>>> list1=list(eval(str1))
>>> list1
['hello', 'world', 100, 12.59, [1, '2', ['3', 4, {'key': 'value'}]]]
>>> list1[4][2][2]['key']
'value'
>>> list1[4][2][0]
'3'
>>> str2=repr(list1)
>>> str2
"['hello', 'world', 100, 12.59, [1, '2', ['3', 4, {'key': 'value'}]]]"
Each and every solution will be appreciated.每一个解决方案都将不胜感激。
Thanks!!!谢谢!!!
You can use Newtonsoft.Json
library to achieve that.您可以使用
Newtonsoft.Json
库来实现这一点。 You need to deserialize the string as a JArray
, as follows:您需要将字符串反序列化为
JArray
,如下所示:
public static void Main()
{
var arr = "['hello', 'world', 100, 12.59, [1, '2', ['3', 4, {'key': 'value'}]]]";
var parsed = JsonConvert.DeserializeObject<JArray>(arr);
Console.WriteLine(parsed[4][2][2]["key"]);
}
You can see a live demo here .您可以在此处查看现场演示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.