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

时间:2019-02-12 14:25:21

标签: c# arrays json visual-studio-2017

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

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

[^\d\s]

2 个答案:

答案 0 :(得分:5)

当然可以!

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

例如:

/*
 * 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();
    }
}

输出

Value : 3
Attribute : Laayelbxw
Value : 1
Attribute : Leruaret
Value : 8
Attribute : Lscwbryeiyabwaa
Value : 9
Attribute : Leruxyklrwbwaa

答案 1 :(得分:3)

会是这样的。

public class JsonExample
{
    public int VALUE { get; set; }

    public string ATTRIBUTE { get; set; }
}

public void GetJson()
{
    string json = "your string";
    var xpto = JsonConvert.DeserializeObject<List<JsonExample>>(json);
}