如何将Newtonsoft JSON与子数组元素一起使用

时间:2016-12-09 08:07:41

标签: c# json.net

{
  "authType": "BASIC",
  "ipAddress": "192.168.210.152",
  "methodLog": [
    {
      "count": 12,
      "methodName": "getPrefixLicensee",
      "lastAccessTimestamp": 1475574521425,
      "firstAccessTimestamp": 1475563584777
    }
  ],
  "requesterGLN": "9501101020016",
  "onBehalfOfGLN": "9501101020016",
  "totalAccessCount": 12,
  "accessCountPer24Hrs": 12,
  "lastAccessTimestamp": 1475574521425,
  "firstAccessTimestamp": 1475563584777,
  "firstAccessWithin24hrsTimestamp": 1475563584777
}

如何使用Newtonsoft JSON获取methodLog中的值?

谢谢, 约翰

2 个答案:

答案 0 :(得分:0)

您可以通过为子数据创建类来使用它,并将该子数据类用作父类中的数据类型,然后您可以使用它。

像...

public class MethodLog
{
    public int count { get; set; }
    public string methodName { get; set; }
    public string lastAccessTimestamp { get; set; }
    public bool firstAccessTimestamp { get; set; }
}

public class Data
{
    public string authType { get; set; }
    public string ipAddress { get; set; }
    public List<MethodLog> MethodLog{ get; set; }
    public string requesterGLN { get; set; }
    public string onBehalfOfGLN { get; set; }
    public int totalAccessCount { get; set; }
    public int accessCountPer24Hrs { get; set; }
    public string lastAccessTimestamp { get; set; }
    public string firstAccessTimestamp { get; set; }
    public string firstAccessWithin24hrsTimestamp { get; set; }
}

public class SingleData
{
    public Data data { get; set; }
}
  

注意: - 您可以根据需要更改数据类型

答案 1 :(得分:0)

只需为对象创建类并使用DeserializeObject<T>

void Main()
{
    var json = File.ReadAllText(@"C:\pathtojson.json");
    var result = JsonConvert.DeserializeObject<RootObject>(json);
    //Generic Linqpad output:
    result.methodLog.Dump();

}

public class MethodLog
{
    public int count { get; set; }
    public string methodName { get; set; }
    public long lastAccessTimestamp { get; set; }
    public long firstAccessTimestamp { get; set; }
}

public class RootObject
{
    public string authType { get; set; }
    public string ipAddress { get; set; }
    public List<MethodLog> methodLog { get; set; }
    public string requesterGLN { get; set; }
    public string onBehalfOfGLN { get; set; }
    public int totalAccessCount { get; set; }
    public int accessCountPer24Hrs { get; set; }
    public long lastAccessTimestamp { get; set; }
    public long firstAccessTimestamp { get; set; }
    public long firstAccessWithin24hrsTimestamp { get; set; }
}

结果:

enter image description here