JConstructor and JRaw in Json.NET

According to this answer on StackOverflow:

Json.NET includes many features that are not part of the JSON specification. In particular, it allows you to parse some JSON files that are "officially" invalid. This includes unquoted properties, comments, constructors, etc.

These are all types assigned from JToken :

 JArray JConstructor JContainer JObject JProperty JRaw JValue 

Tell me if the following is true:

  • It is not possible for JToken.Parse(json) on an "officially" valid json to contain a JConstructor or JRaw in its descendants.

  • Provided that json is "officially" valid, it can be expected that only the following types will be visible in these descendants: JArray , JObject , JProperty , JValue .

+1
source share
1 answer

Your statements are correct.

  • JConstructor designed to enable date capture in JavaScript Date Format , for example: new Date(1234656000000) . As noted in Date Serialization in JSON :

    Technically, this is invalid JSON according to the specification, but all browsers and some JSON frameworks, including Json.NET, support it.

    Thus, the JConstructor will not be displayed when parsing a JSON that strictly conforms to the current IETF standard or the original JSON clause .

    JRaw will never appear when parsing JSON using JToken.Parse(string) . This is useful mainly to facilitate writing pre-formatted JSON literals from the JToken hierarchy. Using JRaw , you can avoid parsing already formatted JSON just to retrieve it, for example:

      var root = new JObject(new JProperty("response", new JRaw(jsonLiteral))); var rootJson = root.ToString(); 

    can be done instead of less efficient:

      var root = new JObject(new JProperty("response", JToken.Parse(jsonLiteral))); 

    You can also deserialize to JRaw to grab the JSON hierarchy as a single string literal, although I don't see much point in that. For example, given the class:

     public class RootObject { public JRaw response { get; set; } } 

    You can do:

      var rootDeserialized = JsonConvert.DeserializeObject<RootObject>(rootJson); var jsonLiteralDeserialized = (string)rootDeserialized.response; 

    However, this is not necessarily more efficient than deserialization for a JToken .

  • As you might guess, when parsing a strictly valid JSON, only JArray , JObject , JProperty and JValue .

+2
source

Source: https://habr.com/ru/post/1264072/


All Articles