我可以在C#中使用JSON字符串吗?

0 c# arrays json visual-studio-2017

重建我在Windows Visual Studio中构建的android应用程序.需要有关在Visual Studio Visual C#Forms应用程序(.NET Framework)中使用JSON字符串的帮助.

我正在创建一种新的文件格式,以便能够将数据传输到我公司的不同机器人.我为我的Android应用程序使用了一个列表映射,该文件包含一个JSON字符串.是否可以将字符串添加到Visual C#Forms(.NET Framework)上的列表中以便在列表框中查看?提供样品.

[{"VALUE":"03","ATTRIBUTE":"Laayelbxw"},
 {"VALUE":"01","ATTRIBUTE":"Leruaret"},
 {"VALUE":"08","ATTRIBUTE":"Lscwbryeiyabwaa"},
 {"VALUE":"09","ATTRIBUTE":"Leruxyklrwbwaa"}]
Run Code Online (Sandbox Code Playgroud)

Cid*_*Cid 5

当然可以 !

我知道在C#中反序列化JSON的最简单方法是使用Newtonsoft Json nuget包.

例如:

/*
 * This class represent a single item of your collection.
 * It has the same properties name than your JSON string members
 * You can use differents properties names, but you'll have to use attributes
 */
class MyClass
{
    public int VALUE { get; set; }
    public string ATTRIBUTE { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var myJSON = "[{\"VALUE\":\"03\",\"ATTRIBUTE\":\"Laayelbxw\"},{\"VALUE\":\"01\",\"ATTRIBUTE\":\"Leruaret\"},{\"VALUE\":\"08\",\"ATTRIBUTE\":\"Lscwbryeiyabwaa\"},{\"VALUE\":\"09\",\"ATTRIBUTE\":\"Leruxyklrwbwaa\"}]";

        //                 V---------V----- Namespace is Newtonsoft.Json
        var MyCollection = JsonConvert.DeserializeObject<List<MyClass>>(myJSON);
        // Tadaam ! You now have a collection of MyClass objects created from that json string

        foreach (var item in MyCollection)
        {
            Console.WriteLine("Value : " + item.VALUE);
            Console.WriteLine("Attribute : " + item.ATTRIBUTE);
        }
        Console.Read();
    }
}
Run Code Online (Sandbox Code Playgroud)

产量

Value : 3
Attribute : Laayelbxw
Value : 1
Attribute : Leruaret
Value : 8
Attribute : Lscwbryeiyabwaa
Value : 9
Attribute : Leruxyklrwbwaa
Run Code Online (Sandbox Code Playgroud)