c# - 将 JSON 字符串反序列化为 C# 对象
问题描述
我有以下 json 字符串
[
{
"data": {
"vehicle_number": "HR38Y1539",
"device_id": "0358735074626234",
"type": "we_track",
"cordinate": [
"28.427771",
"77.018409"
],
"address": "Haryana",
"city": "",
"state": "",
"motion_status": "halt",
"motion_state": "stopped",
"speed": 0,
"orientation": "306",
"last_received_at": 1555407765,
"share_link": "https://loconav.com/track-a-day/541387a344",
"custom_data": {}
}
},
{
"data": {
"vehicle_number": "UP63AE7715",
"device_id": "0866551031969632",
"type": "gt06mini",
"cordinate": [
"28.757673",
"77.160532"
],
"address": "Ganpati Sachidanand Datta Marg,Swaroop Nagar,Bhalswa,Delhi,North West Delhi",
"city": "",
"state": "",
"motion_status": "halt",
"motion_state": "moving",
"speed": 0,
"orientation": "243",
"last_received_at": 1555407768,
"share_link": "https://loconav.com/track-a-day/54961f9617",
"custom_data": {}
}
}]
我想将其反序列化为自定义的 c# 对象或数据表。我尝试制作各种类定义,但没有一个成功。对此的任何帮助将不胜感激。
编辑:
我为这个json做了以下类:
public class CustomData
{
}
public class VehicleData
{
public string vehicle_number { get; set; }
public string device_id { get; set; }
public string type { get; set; }
public List<string> cordinate { get; set; }
public string address { get; set; }
public string city { get; set; }
public string state { get; set; }
public string motion_status { get; set; }
public string motion_state { get; set; }
public int speed { get; set; }
public string orientation { get; set; }
public int last_received_at { get; set; }
public string share_link { get; set; }
public CustomData custom_data { get; set; }
}
public class AUL_Json_Data
{
public VehicleData data { get; set; }
}
我正在使用以下代码进行反序列化:
AUL_Json_Data truckData = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<AUL_Json_Data>(json);
但它给出了一个例外:数组的反序列化不支持类型'AUL_Json_Data'。
解决方案
将此模型用于您的 Json:
public class Data
{
public string vehicle_number { get; set; }
public string device_id { get; set; }
public string type { get; set; }
public List<string> cordinate { get; set; }
public string address { get; set; }
public string city { get; set; }
public string state { get; set; }
public string motion_status { get; set; }
public string motion_state { get; set; }
public int speed { get; set; }
public string orientation { get; set; }
public int last_received_at { get; set; }
public string share_link { get; set; }
public CustomData custom_data { get; set; }
}
public class RootObject
{
public Data data { get; set; }
}
public class CustomData
{
}
然后以这种方式反序列化它
var Data = JsonConvert.DeserializeObject<List<RootObject>>(data);
推荐阅读
- html - 如何将我的 create-react-app 项目变成带有嵌入 js 的单个 html 文件?
- python - 如何在opencv中使用光流跟踪来分割图像?
- python - 用python在数组中选择单词的问题
- reactjs - 使用单个操作修改多个值或每个值的操作的优缺点是什么?为什么?
- html - ATOM 文本编辑器文本颜色因哈希而改变
- java - 有没有办法从特定行的列中获取值并将其放入下一行?
- java - aui 验证器无法处理 liferay 中的表单提交
- javascript - 有没有办法在 laracast flash 中改变生命时间?
- python - 如何根据连续索引拆分数据框?
- ios - 应用程序在后台时没有立即调用 DidRecieveRemoteNotification