使用c#迭代动态json属性

时间:2018-04-15 15:10:06

标签: c# json dynamic

在我处理一些JSON文件的项目中,JSON的结构如下:

{"mid":"1",
  "Engine":{ //Engine is dynamic and may not be available in all data
    "gid":"1",
    "parameters":{
      "Gross Power":{"pid":"1"},
      "PTO Power":{"pid":"2"},
      "Power Measured @":{"pid":"3"},
      "Displacement":{"pid":"4"},
      "Aspiration":{"pid":"5"}
    }
  },
  "Operational":{//Operational is optional too and might not be available in all cases
    "gid":"2",
    "parameters":{
      "Operating Weight":{"pid":"12"},
      "Fuel Capacity":{"pid":"13"}
    }
  },
  "Transmission":{//Transmission is optional like others
    "gid":"3",
    "parameters":{
      "Type":{"pid":"24"},
      "Number of Forward Gears":{"pid":"25"}
    }
  }
}

因此,您看到每个组都有不同的标签,现在我想要做的是对JSON数据进行操作并执行以下操作:

dynamic obj = JsonConvert.DeserializeObject(JSON);
Console.WriteLine((int) obj.Engine.gid);

但由于Engine是标签和动态,因此我如何指向JSON文件中的动态标签。

PS:我使用Newtonsoft Json.net库来反序列化Object。

1 个答案:

答案 0 :(得分:0)

只需声明如下的模型

public class Pid
{
    public string pid { get; set; }
}


public class Parameters
{
    [JsonProperty("Gross Power")]
    public Pid GrossPower { get; set; }
    [JsonProperty("PTO Power")]
    public Pid PTOPower { get; set; }
    [JsonProperty("Power Measured @")]
    public Pid PowerMeasured { get; set; }
    public Pid Displacement { get; set; }
    public Pid Aspiration { get; set; }
}

public class Engine
{
    public string gid { get; set; }
    public Parameters parameters { get; set; }
}



public class Parameters2
{
    [JsonProperty("Operating Weight")]
    public Pid OperatingWeight { get; set; }
    [JsonProperty("Fuel Capacity")]
    public Pid FuelCapacity { get; set; }
}

public class Operational
{
    public string gid { get; set; }
    public Parameters2 parameters { get; set; }
}


public class Parameters3
{
    public Pid Type { get; set; }
    [JsonProperty("Number Of Forward Gears")]
    public Pid NumberOfForwardGears { get; set; }
}

public class Transmission
{
    public string gid { get; set; }
    public Parameters3 parameters { get; set; }
}

public class RootObject
{
    public string mid { get; set; }
    public Engine Engine { get; set; }
    public Operational Operational { get; set; }
    public Transmission Transmission { get; set; }
}

并将其用作

var myObj = JsonConvert.DeserializeObject<RootObject>(json);