簡體   English   中英

在c#中將包含數組和字典的字符串轉換為列表,反之亦然

[英]Convert the string containing array and dict into the 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'}]]]

預期成績:

Console.WriteLine(List1[0])               //Output: 'hello'

Console.WriteLine(List1[4][2][1])         //Output:  4

Console.WriteLine(List1[4][2][2]['key'])  //Output: 'value'

筆記:

python 中,我們有一個eval(expression)方法可以將字符串轉換為列表

我們有一個repr(obj)方法將列表轉換回字符串

請使用python方法參考以下示例代碼。 我需要在 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'}]]]"

每一個解決方案都將不勝感激。

謝謝!!!

您可以使用Newtonsoft.Json庫來實現這一點。 您需要將字符串反序列化為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"]);
}

您可以在此處查看現場演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM