反序列化复杂json时获取NULL值

时间:2019-02-07 12:33:33

标签: c# json deserialization

我的项目有一个第三方Web API,该API返回以下格式的json字符串(包括大括号的开头和结尾):

{ 
   "866968030210604":{
      "dt_server":"2019-02-07 12:21:27",
      "dt_tracker":"2019-02-07 12:21:27",
      "lat":"28.844968",
      "lng":"76.858502",
      "altitude":"0",
      "angle":"154",
      "speed":"9",
      "params":{
         "pump":"0",
         "track":"1",
         "bats":"1",
         "acc":"0",
         "batl":"4"
      },
      "loc_valid":"1"
   },
   "866968030221205":{
      "dt_server":"2019-02-07 12:20:24",
      "dt_tracker":"2019-02-07 12:19:41",
      "lat":"28.845904",
      "lng":"77.096063",
      "altitude":"0",
      "angle":"0",
      "speed":"0",
      "params":{
         "pump":"0",
         "track":"1",
         "bats":"1",
         "acc":"0",
         "batl":"4"
      },
      "loc_valid":"1"
   },
   "866968030212030":{
      "dt_server":"0000-00-00 00:00:00",
      "dt_tracker":"0000-00-00 00:00:00",
      "lat":"0",
      "lng":"0",
      "altitude":"0",
      "angle":"0",
      "speed":"0",
      "params":null,
      "loc_valid":"0"
   }
}

我想将其反序列化为c#类对象以进行进一步处理。我为相同的对象制作了以下类结构:

class Params
{
    public string pump { get; set; }
    public string track { get; set; }
    public string bats { get; set; }
    public string acc { get; set; }
    public string batl { get; set; }
}

class GPSData
{
    public string dt_server { get; set; }
    public string dt_tracker { get; set; }
    public string lat { get; set; }
    public string lng { get; set; }
    public string altitude { get; set; }
    public string angle { get; set; }
    public string speed { get; set; }
    public Params ObjParams { get; set; }
    public string loc_valid { get; set; }
}

并且我正在尝试以下代码进行反序列化:

JavaScriptSerializer jSerObj = new JavaScriptSerializer();

List<GPSData> lstGPSData = (List<GPSData>)jSerObj.Deserialize(json, typeof(List<GPSData>));

但是每次调用Deserialize()方法后,每次显示分配给该类的每个属性的NULL值。请帮助我。

1 个答案:

答案 0 :(得分:2)

您的json不在列表格式中,因此反序列化为 studentObj.FeesCollectionPending = paymentlist; 无效

所以您需要像

一样将其反序列化为List<>
Dictionary<string, GPSData>

用法:

JavaScriptSerializer jSerObj = new JavaScriptSerializer();

Dictionary<string, GPSData> lstGPSData = (Dictionary<string, GPSData>)jSerObj.Deserialize(json, typeof(Dictionary<string, GPSData>));

此外,您可以从上面的字典中列出所有foreach (var item in lstGPSData) { string key = item.Key; GPSData gPSData = item.Value; } ,例如

GPSData

输出:(来自调试器)

enter image description here