简体   繁体   English

C#json对象用于动态属性

[英]C# json object for dynamic properties

I need to output this json: 我需要输出这个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? 任何线索?

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: 结果在这个json:

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

Fiddle here 在这里小提琴

If you don't mind using an extra library, try Json.Net (ASP.net has this pre-installed). 如果您不介意使用额外的库,请尝试Json.Net (ASP.net已预先安装)。 All you have to do is 你所要做的就是

dynamic result = JsonConvert.DeserializeObject(json);

If I remember correctly, to access a value, use result[0].Value; 如果我没记错,要访问一个值,请使用result[0].Value;

Json.NET is the library used by almost all ASP.NET projects, including ASP.NET Web API and all ASP.NET Core projects. Json.NET是几乎所有ASP.NET项目使用的库,包括ASP.NET Web API和所有ASP.NET Core项目。 It can deserialize JSON to a strongly typed object or parse it to a weakly typed JObject, or generate JSON from any object. 它可以将JSON反序列化为强类型对象,或者将其解析为弱类型的JObject,或者从任何对象生成JSON。 There is no need to create special classes or objects. 无需创建特殊的类或对象。

You can serialize any object to a Json string with JsonConvert.SerializeObject 您可以使用JsonConvert.SerializeObject将任何对象序列化为Json字符串

var json=JsonConvert.SerializeObject(someObject);

Or you can use JObject as a dynamic object and convert it directly to a string : 或者您可以将JObject用作dynamic对象并将其直接转换为字符串:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM