1

I need to generate Json-output like this:

{
    "01:30":{
        "FREE":true,
        "PRICE":3500
     },
    "03:00":{
        "FREE":true,
        "PRICE":2500
    },
    "13:30":{
        "FREE":true,
        "PRICE":2500
    }
}

My problem here is time string - its dynamic from one entry to another. I can not figure out how to construct my c# class (model) that will be serialized into proper json result. My model looks like this now:

public class ScheduleViewModel
{
    public ScheduleInnerViewModel TIME { get; set; }
}

public class ScheduleInnerViewModel
{
    public bool FREE { get; set; }
    public int PRICE { get; set; }
}

Output result is (wrong):

[
    {"TIME":{
        "FREE":true,
        "PRICE":3500
     }},
    {"TIME":{
        "FREE":true,
        "PRICE":2500
    }},
    {"TIME":{
        "FREE":true,
        "PRICE":2500
    }}
]

I use standard way to generate json result from controller:

List<ScheduleViewModel> model = new List<ScheduleViewModel>();
//fill the model...
return this.Json(model, JsonRequestBehavior.AllowGet);
1
  • "01:30" you need a variable to represent this Commented Jun 28, 2016 at 16:48

2 Answers 2

2

What about having a dictionary where the key is a string (your timestamp) and the data is your model class ?

Like:

Dictionary<string, ScheduleInnerViewModel> dic = new Dictionary<string, ScheduleInnerViewModel>();

dic.Add("01:30", new ScheduleInnerViewModel{ Free = false, Price = 100 });
dic.Add("04:25", new ScheduleInnerViewModel{ Free = false, Price = 200 });
dic.Add("13:00", new ScheduleInnerViewModel{ Free = true, Price = 0 });

var json = JsonConvert.SerializeObject(dic, new JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented });

Console.WriteLine(json);

Output:

enter image description here

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

1 Comment

Thank you! Simple and elegant solution.
2

Try the unaccepted answer from this post. It uses a Dictionary to create the property name (key) and then you can use your ScheduleInnerViewModel as the value so something like:

 var obj = new Dictionary<string, ScheduleInnerViewModel>();

1 Comment

seems I came a minute late :)

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.