4

I need to output this json:

{
      white: [0, 60],
      green: [60, 1800],
      yellow: [1800, 3000],
      red: [3000, 0]
}

And I was trying to think on a model like:

 public class Colors
    {

        public int[] white { get; set; }

        public int[] green { get; set; }

        public int[] yellow { get; set; }

        public int[] red { get; set; }
    }

But the property names could change, like maybe white can be now gray, etc.

Any clue?

12
  • 2
    What about a Dictionary<string, int[]>? You wouldnt need that Colors class at all Commented Feb 22, 2018 at 15:01
  • Look into DataContract classes and the System.ComponentModel namespace Commented Feb 22, 2018 at 15:01
  • You desired JSON format is invalid, you would have " wrapping your field names in JSON Commented Feb 22, 2018 at 15:02
  • 1
    First ensure you're really producing json since that's not legal json. Your properties are missing quotes, if it is supposed to be json it has to be "white": [0, 60], "green": [60, 1800], etc. Other than that, you're looking for a simple dictionary like @maccettura commented. Commented Feb 22, 2018 at 15:05
  • 1
    @styx why? JSON.Net can already return weakly-typed objects or deserialize to dynamic Commented Feb 22, 2018 at 15:06

3 Answers 3

8

All you need is a Dictionary:

Dictionary<string, int[]> dictionary = new Dictionary<string, int[]>();

dictionary.Add("white", new int[] { 0, 60 });
dictionary.Add("green", new int[] { 60, 1800 });
dictionary.Add("yellow", new int[] { 1800, 3000 });
dictionary.Add("red", new int[] { 3000, 0 });

//JSON.NET to serialize
string outputJson = JsonConvert.SerializeObject(dictionary)

Results in this json:

{
    "white": [0, 60],
    "green": [60, 1800],
    "yellow": [1800, 3000],
    "red": [3000, 0]
}

Fiddle here

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

6 Comments

No need for that since Json.NET returns a weakly-typed object when parsing arbitrary strings. It's deserialization that requires a strongly typed object.
@PanagiotisKanavos I don't understand what you are saying. If JSON.NET is parsing strings, wouldnt that be deserialization? In which case, by your own comment, it would require a strongly typed object? OP wants to generate a specific JSON that is very clearly a string/int[] Dictionary, what solution would be better than that?
A simple JObject.ToString()
The fiddle includes that, I can add it to the answer body. OP had a high enough reputation where I assumed they did not need help with the actual serialization, but how to make a "dynamic" object to serialize
@maccettura thanks for edit, upvoted. Please do not forget that your answer could be usefull not only for OP. Also link to fiddle can become broken after some time, but after your last edit your answer is self contained.
|
2

If you don't mind using an extra library, try Json.Net (ASP.net has this pre-installed). All you have to do is

dynamic result = JsonConvert.DeserializeObject(json);

If I remember correctly, to access a value, use result[0].Value;

3 Comments

Json.NET isn't an extra library, it's the built-in default for ASP.NET Web API and the Core templates
@TheMCProgrammer I was partially wrong, it is built in to .NET Core, but on the other project types it is just an optional nuget package
Gotcha, that makes sense.
1

Json.NET is the library used by almost all ASP.NET projects, including ASP.NET Web API and all ASP.NET Core projects. It can deserialize JSON to a strongly typed object or parse it to a weakly typed JObject, or generate JSON from any object. There is no need to create special classes or objects.

You can serialize any object to a Json string with JsonConvert.SerializeObject

var json=JsonConvert.SerializeObject(someObject);

Or you can use JObject as a dynamic object and convert it directly to a string :

dynamic product = new JObject();
product.ProductName = "Elbow Grease";
product.Enabled = true;
product.Price = 4.90m;
product.StockCount = 9000;
product.StockValue = 44100;
product.Tags = new JArray("Real", "OnSale");

Console.WriteLine(product.ToString());

Comments

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.