JToken: Get raw/original JSON value

前端 未结 3 608
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-27 07:28

Is there a way to get the raw/original JSON value from a JToken?

The problem:

var data = JObject.Parse(@\"{
    \"\"SimpleDate\"\":\"\"         


        
相关标签:
3条回答
  • 2020-11-27 08:07

    There's a solution I found in Json.NET Disable the deserialization on DateTime:

    JsonReader reader = new JsonTextReader(new StringReader(j1.ToString()));
    reader.DateParseHandling = DateParseHandling.None;
    JObject o = JObject.Load(reader);
    
    0 讨论(0)
  • 2020-11-27 08:14

    You cannot get the original string, date strings are recognized and converted to DateTime structs inside the JsonReader itself. You can see this if you do:

    Console.WriteLine(((JValue)data["SimpleDate"]).Value.GetType()); // Prints System.DateTime
    

    You can, however, extract the dates in ISO 8601 format by doing:

    var value = JsonConvert.SerializeObject(data["SimpleDate"]);
    // value is "2012-05-18T00:00:00Z"
    

    This will always output a JValue in a JSON-appropriate string format. Since your original dates are in this format, this may meet your needs.

    (Honestly, I'm surprised JValue.ToString() outputs dates in non-ISO format, given that JObject.ToString() does output contained dates in ISO format.)

    If you were able to change settings while reading your JObject, you could use JsonSerializerSettings.DateParseHandling = DateParseHandling.None:

            var settings = new JsonSerializerSettings { DateParseHandling = DateParseHandling.None };
            var data = JsonConvert.DeserializeObject<JObject>(@"{
                ""SimpleDate"":""2012-05-18T00:00:00Z"",
                ""PatternDate"":""2012-11-07T00:00:00Z""
            }", settings);
    
            var value = data["SimpleDate"].Value<string>();
    
            Debug.WriteLine(value); // Outputs 2012-05-18T00:00:00Z
    

    There's no overload to JObject.Parse() that takes a JsonSerializerSettings, so you would need to use DeserializeObject. This setting eventually gets propagated to JsonReader.DateParseHandling.

    0 讨论(0)
  • 2020-11-27 08:20

    another approach - that would work - Regex

    SimpleDate(?:.*):(?:.*?)\"([0-9|-]{1,}T[0-9|:]+Z)
    

    it is a regex pattern to extract the data you look for - you just wanted the string, so here it is . it is not the JSON parsing approach - but it indeed extracts the string.

    here is a sample of how it works

    0 讨论(0)
提交回复
热议问题