C#json对象用于动态属性

时间:2018-02-22 14:59:32

标签: c# json

我需要输出这个json:

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

我试图想像这样的模型:

 public class Colors
    {

        public int[] white { get; set; }

        public int[] green { get; set; }

        public int[] yellow { get; set; }

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

但是属性名称可能会改变,就像白色现在可能是灰色等等。

有任何线索吗?

3 个答案:

答案 0 :(得分:5)

你需要的只是一个词典:

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)

结果在这个json:

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

小提琴here

答案 1 :(得分:2)

如果您不介意使用额外的库,请尝试Json.Net(ASP.net已预先安装)。 你所要做的就是

p

如果我没记错,要使用dynamic result = JsonConvert.DeserializeObject(json);

,要访问某个值

答案 2 :(得分:1)

Json.NET是几乎所有ASP.NET项目使用的库,包括ASP.NET Web API和所有ASP.NET Core项目。它可以将JSON反序列化为强类型对象,或者将其解析为弱类型的JObject,或者从任何对象生成JSON。无需创建特殊的类或对象。

您可以使用JsonConvert.SerializeObject

将任何对象序列化为Json字符串
var json=JsonConvert.SerializeObject(someObject);

或者您可以将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());