Fearcoder
Fearcoder

Reputation: 788

Converting a complex JSON object into a C# property

I am struggling to build a complex JSON object this is what I want:

{"name": [ "failed","complete"], "data": ["failed":[1, 2, 3], "completed": [1, 2, 3]}

I want to convert this in a C# class as a property. There must be a connection with the failed property and the list of int. The output must be:

failed: 1, 2, 3 complete: 1,2 ,3

What is the correct syntax of a JSON object like this? And how can I declare a property of this object in c#?

I was thinking about dictionaries but maybe there is a better way?

Kind regards

Upvotes: 1

Views: 95

Answers (1)

ahmad molaie
ahmad molaie

Reputation: 1540

I think it should be :

{"name": [ "failed","complete"], "data": {"failed":[1, 2, 3], "completed": [1, 2, 3]}}

then you can use :

public class Data {
    public List<int> failed { get; set; }
    public List<int> completed { get; set; }
}

public class RootObject {
    public List<string> name { get; set; }
    public Data data { get; set; }
}

and for any json to c#, I use : json2csharp.com

EDIT: I think, a better approach for your case is using dictionary and following class:

public class DataValues {
    public List<int> Data;
}

and then use it like :

Dictionary<string, DataValues> x = new Dictionary<string, DataValues>();

x.Add("failed", new DataValues() {
    Data = new List<int> { 1, 2, 3 }
});
x.Add("complete", new DataValues() {
    Data = new List<int> { 1, 2, 3 }
});

var resultinJson = new JavaScriptSerializer().Serialize(x);

Then, the Json result is :

{
    "failed": {
        "Data": [1, 2, 3]
    },
    "complete": {
        "Data": [1, 2, 3]
    }
}

obviously, you can add more status or step or what ever it is called in your app. to it.

Upvotes: 2

Related Questions