0

I need to define in a json file bands containing a dynamic value ranges configuration. They might change in future, so I would like it to look like this:

"Bands": {
    "5-15": [ 5000, 15000 ],
    "15-30": [ 15000, 30000 ],
    "30-45": [ 30000, 45000 ],
    "45-60": [ 45000, 60000 ],
    "60-100": [ 60000, 100000 ]
}

Is it possible to read with this json format and store it in an object?

I tried this:

public class BandsMapping
{
    public List<Bands> Bands { get; set; }
}

public class Bands
{
    public string Name { get; set; }
    public List<int> ValueRanges { get; set; }
}

But it fails because there's no Name neither ValueRanges in the json file. But I would like the json file to look something like this.

Any idea on how can I achieve that?

2
  • 2
    I suspect you can deserialize the JSON for Bands into a Dictionary<string, int[]> and then convert it to the mapping you want. Commented Jun 17, 2020 at 11:42
  • Exactly as you suspected :) Commented Jun 17, 2020 at 14:42

1 Answer 1

1

You can use Dictionary<string, List<int>> or Dictionary<string, int[]> for Bands content instead of just List<int>

public class BandsMapping
{
    public Dictionary<string, List<int>> Bands { get; set; }
}

Dictionary key represents a string with range, dictionary value is an array or list of integer values. You can also easily convert the dictionary into list of Bands items using Select method

var result = JsonConvert.DeserializeObject<BandsMapping>(jsonString);
var bandsList = result.Bands
    .Select(kvp => new Bands { Name = kvp.Key, ValueRanges = kvp.Value })
    .ToList();
Sign up to request clarification or add additional context in comments.

2 Comments

It wasn't me! And it did work :) Thanks ^^ They are also downvoting my question and don't understand the reason...
I swear I thougth this was an old post. Exact same type of dupe exact same comment.

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.