Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
600 views
in Technique[技术] by (71.8m points)

c# - JConstructor and JRaw in Json.NET

According to this answer on StackOverflow:

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

These are all the types assignable from JToken:

JArray
JConstructor
JContainer
JObject
JProperty
JRaw
JValue

Please tell if the following are true:

  1. It is not possible that JToken.Parse(json) on an "officially" valid json will in its descendants contain JConstructor or JRaw.

  2. Provided that a json is "officially" valid, one can expect only the following types to see in those descendants: JArray, JObject, JProperty, JValue.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your statements are true.

  1. JConstructor is designed to enable capture of dates in JavaScript Date format, e.g.: new Date(1234656000000). As noted in Serializing Dates in JSON:

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

    Thus JConstructor will not appear when parsing JSON that conforms strictly to the current IETF proposed standard or the original JSON proposal.

JRaw will never appear when parsing JSON using JToken.Parse(string). It is useful mainly to facilitate writing of pre-formatted JSON literals from a JToken hierarchy. By using JRaw, one can avoid parsing the already-formatted JSON simply in order to emit it, e.g.:

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

can be done instead of the less-efficient:

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

It's also possible to deserialize to `JRaw` to capture a JSON hierarchy as a single string literal, though I don't see much use in doing so.  For instance, given the class:

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

One can do:<p>

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

However, this is not necessarily more efficient than deserializing to a `JToken`.
  1. As you surmise, only JArray, JObject, JProperty and JValue will appear when parsing strictly valid JSON.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...