举个例子,有这样一段代码,其中包含一个自定义类BatteryStatus
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
using Newtonsoft.Json; using System; namespace ConsoleApp2 { internal class Program { public class BatteryStatus { // The battery level reports percentage of the full battery.The field can take values from 0 to 100% (0x00 – 0x64). // The value 0xFF indicates a battery low warning. public byte BatteryLevel { get; set; } public bool LowBatteryWarning { get; set; } public DateTime TimestampUtc { get; set; } public BatteryStatus(byte batteryLevel) { TimestampUtc = DateTime.UtcNow; if (batteryLevel == 0xff) { LowBatteryWarning = true; batteryLevel = 0; } BatteryLevel = batteryLevel; } } static void Main(string[] args) { BatteryStatus batteryStatus = new BatteryStatus(40); string json = SaveObjectToJsonString(batteryStatus); Object obj = ReadObjectFromJsonString(json); } static string SaveObjectToJsonString(Object obj) { string json = JsonConvert.SerializeObject(obj); return json; } static Object ReadObjectFromJsonString(string json) { var obj = JsonConvert.DeserializeObject(json); return obj; } } } |
如果不更改SaveObjectToString或ReadObjectFromString函数(并假设您甚至没有看到这些函数的源代码),如何将obj转换为BatteryStatus类的对象?
强制转换是不行的:
batteryStatus = (BatteryStatus)obj;
这会导致以下错误:
无法将类型’Newtonsoft.Json.Linq.JObject的对象强制转换为类型“BatteryStatus”。
正确的办法是使用 JObject的 ToObject<>函数,如下:
1 |
var deserializedBatteryStatus = (jObj as JObject).ToObject<BatteryStatus>(); |