1

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

5
  • 4
    That's not valid json, so you'll have to write your own interpreter. Commented Feb 9, 2018 at 14:16
  • 1
    Assuming you fix the missing ], in Visual Studio: Edit -> Paste Special -> Paste as JSON Classes. Commented Feb 9, 2018 at 14:19
  • @crashmstr like this? {"name": [ "failed","complete"], "data": ["failed":[1, 2, 3], "completed": [1, 2, 3]]} Commented Feb 9, 2018 at 14:21
  • 1
    If data is an array of objects, you need { "name": [ "failed", "complete" ], "data": [ { "failed": [ ... ], "completed": [ ... ] } ] }, if data is a single object, { "name": [ "failed", "complete" ], "data": { "failed": [ ... ], "completed": [ ... ] } } Commented Feb 9, 2018 at 14:27
  • You can use some online json class converter and NewtonSoft JsonConvert.DeserializeObject<T>(jsonString) method. Commented Feb 9, 2018 at 14:32

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you this is exactly what I am looking for have a nice day!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.