Gmanski 156
Gmanski 156

Reputation: 7

Can I use a JSON string in C#?

Rebuilding a java app for android I built in Windows Visual Studio. Need help on using JSON strings in Visual Studio Visual C# Forms app (.NET Framework).

I'm creating a new file format to be able to transfer data to different robots in my company. I used a list map for my android app and the file contains a JSON string. Is it possible to add the string into a list on Visual C# Forms (.NET Framework) for view in a list box? Sample is provided.

[{"VALUE":"03","ATTRIBUTE":"Laayelbxw"},
 {"VALUE":"01","ATTRIBUTE":"Leruaret"},
 {"VALUE":"08","ATTRIBUTE":"Lscwbryeiyabwaa"},
 {"VALUE":"09","ATTRIBUTE":"Leruxyklrwbwaa"}]

Upvotes: 0

Views: 147

Answers (2)

Cid
Cid

Reputation: 15247

Of course you can !

The simpliest way I know to deserialize a JSON in C# is using the Newtonsoft Json nuget package.

In example :

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

Output

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

Upvotes: 5

Jo&#227;o Paulo Amorim
Jo&#227;o Paulo Amorim

Reputation: 436

It's gonna be something like this.

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);
}

Upvotes: 3

Related Questions