JObject.Parse vs JsonConvert.DeserializeObject

后端 未结 4 1237
别跟我提以往
别跟我提以往 2020-12-04 10:59

What\'s the difference between JsonConvert.DeserializeObject and JObject.Parse? As far as I can tell, both take a string and are in the Json.NET library. What kind of situ

4条回答
  •  春和景丽
    2020-12-04 11:49

    JsonConvert.DeserializeObject has one advantage over JObject.Parse: It is possible to use custom JsonSerializerSettings.

    This can be very useful e.g. if you want to control how dates are deserialized. By default dates are deserialized into DateTime objects. This means that you may end up with a date with another time zone than the one in the json string.

    You can change this behaviour by creating a JsonSerializerSetting and setting DateParseHandling to DateParseHandling.DateTimeOffset.

    An example:

    var json = @"{ ""Time"": ""2015-10-28T14:05:22.0091621+00:00""}";
    Console.WriteLine(json);
    // Result: { "Time": "2015-10-28T14:05:22.0091621+00:00" }
    
    var jObject1 = JObject.Parse(json);
    Console.WriteLine(jObject1.ToString());
    // Result: { "Time": "2015-10-28T15:05:22.0091621+01:00" }
    
    var jObject2 = Newtonsoft.Json.JsonConvert.DeserializeObject(json, 
      new Newtonsoft.Json.JsonSerializerSettings 
      { 
        DateParseHandling = Newtonsoft.Json.DateParseHandling.DateTimeOffset 
      });
    Console.WriteLine(jObject2.ToString());
    // Result: { "Time": "2015-10-28T14:05:22.0091621+00:00" }
    

提交回复
热议问题