C# json object for dynamic properties

☆樱花仙子☆ 提交于 2021-02-10 06:20:15

问题


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?


回答1:


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




回答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:


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());


来源:https://stackoverflow.com/questions/48930552/c-sharp-json-object-for-dynamic-properties

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!