How C # recognizes if a string is in JSON format

Source: Internet
Author: User
How C # identifies whether a string is in JSON format:

Using system;using system.collections.generic;using system.text;namespace cyq.    data.tool{//<summary>///delimited JSON string as a dictionary collection.            </summary> Internal class Jsonsplit {private static bool Isjsonstart (ref string JSON) { if (!string. IsNullOrEmpty (JSON)) {JSON = json.                Trim (' \ r ', ' \ n ', '); if (JSON.                    Length > 1) {char s = json[0]; Char e = Json[json.                    LENGTH-1]; return (s = = ' {' && e = = '} ') | |                (s = = ' [' && e = = '] ');        }} return false;            } internal static bool Isjson (string json) {int errindex;        Return Isjson (JSON, out errindex);            } internal static bool Isjson (string json, out int errindex) {errindex = 0;  if (Isjsonstart (ref JSON)) {Charstate cs = new Charstate ();              char c; for (int i = 0; i < JSON. Length;                    i++) {c = json[i];                    if (Setcharstate (c, ref CS) && Cs.childrenstart)//Set key symbol status. {String item = JSON.                        Substring (i);                        int err;                        int length = Getvaluelength (item, True, out err);                        Cs.childrenstart = false;                            if (Err > 0) {errindex = i + err;                        return false;                    } i = i + length-1;                        } if (cs.iserror) {errindex = i;                    return false;            }} return!cs.arraystart &&!cs.jsonstart;        } return false;   }//<summary>     Gets the length of the value (when the JSON value is nested at the beginning of "{" or "[")///</summary> private static int getvaluelength (string json, Boo            L BREAKONERR, out int errindex) {errindex = 0;            int len = 0; if (!string.                IsNullOrEmpty (JSON)) {Charstate cs = new Charstate ();                char c; for (int i = 0; i < JSON. Length;                    i++) {c = json[i]; if (!                    Setcharstate (c, ref CS))//Set key symbol status.                        {if (!cs.jsonstart &&!cs.arraystart)//json end, not an array, exits.                        {break;                    }} else if (Cs.childrenstart)//normal character, value state. {int length = Getvaluelength (JSON.                        Substring (i), Breakonerr, out errindex);//recursive sub-value, return a length ...                        Cs.childrenstart = false; Cs.valuestart = 0;                       cs.state = 0;                    i = i + length-1;                        } if (Breakonerr && cs.iserror) {errindex = i;                    return i;                    } if (!cs.jsonstart &&!cs.arraystart)//record the current end position.                    {len = i + 1;//length peso citation +1 break;        }}} return len;            }///<summary>///character status//</summary> private class Charstate {            internal bool Jsonstart = false;//begins with "{" ... internal bool Setdicvalue = false;//You can set the dictionary value. internal bool Escapechar = false;//begins with the "\" escape sign///<summary>/////array start "Only First", Value nested with "childrens            Tart "to identify. </summary> internal bool Arraystart = false;//begins with the "[" Symbol Internal bool Childrenstart = false;//Child nesting begins. <summary>//"0 initial state, or encountered", "comma"; "1 encountered": "Colon"///</summary> Internal int            state = 0;            <summary>//"1 Value End" "0 Not Started" "1 no quotation marks start" "2 single quote Start" "3 double quotation mark start"//</summary>            internal int keystart = 0;            <summary>//"1 Value End" "0 Not Started" "1 no quotation marks start" "2 single quote Start" "3 double quotation mark start"//</summary>            internal int valuestart = 0;            internal bool IsError = false;//is a syntax error. internal void Checkiserror (char c)//is only processed as a first level (because the getlength is recursive to each child processing) {if (Keystart > 1 | | val                Uestart > 1) {return; }//Example ["AA", {"BBBB": 123, "FFF", "ddd"}] switch (c) {case ' {'://[{' [{A}] ": [{" [{B}] "": 3, "M": "C"}]}] IsError = Jsonstart && state = = 0;//repeat startErrors are not value-handling at the same time.                    Break Case '} ': IsError =!jsonstart | | (Keystart! = 0 && state = = 0);//repeat end error or end prematurely {"AA"}.                    The normal has {} break;                    Case ' [': IsError = arraystart && state = = 0;//repeat start error break; Case '] ': isError =!arraystart | |                    jsonstart;//Duplicate start error or Json does not end break; Case ' ': Case ' \ ': IsError =! (Jsonstart | | arraystart);                        The JSON or array begins.  if (!iserror) {//repeat start ["", {"" "}] IsError = (state = = 0 && Keystart = =-1) | |                        (state = = 1 && Valuestart = =-1);           } if (!iserror && arraystart &&!jsonstart && c = = ' \ ')//[' AA ', {}]             {IsError = true;                    } break; Case ': ': isError =!jsonstart | |                        The state = = 1;//repeats itself.                    Break Case ', ': IsError =! (Jsonstart | | arraystart);                        The JSON or array begins.                                if (!iserror) {if (Jsonstart) { IsError = state = = 0 | |                            (state = = 1 && valuestart > 1);//repeated appearance.                                } else if (arraystart)//["AA," [,] [{},{}] {                            IsError = Keystart = = 0 &&!setdicvalue;                    }} break; Case ': Case ' \ r ': Case ' \ n '://["a", \r\n{}] Case' + ': case ' \ t ': break;                        Default://value begins with. IsError = (!jsonstart &&!arraystart) | | (state = = 0 && Keystart = =-1) | |                (Valuestart = =-1 && state = = 1);//break;        }//if (IsError)//{//}}}//<summary> Sets the character state (returns true as the keyword, returns false when the normal character is processed)///</summary> private static bool Setcharstate (char C, r EF Charstate CS) {cs.            Checkiserror (c);                    Switch (c) {case ' {'://[{"[{A}]": [{"[{B}]": 3, "M": "C"}]}] #region curly braces if (cs.keystart <= 0 && cs.valuestart <= 0) {Cs.keys                        Tart = 0;                        Cs.valuestart = 0;                      if (cs.jsonstart && cs.state = = 1)  {Cs.childrenstart = true;                        } else {cs.state = 0;                        } Cs.jsonstart = true;//started.                    return true;                } #endregion break; Case '} ': #region curly braces End if (cs.keystart <= 0 && Cs.valuestart < 2 &amp                        ;& cs.jsonstart) {Cs.jsonstart = false;//ends normally.                        cs.state = 0;                        Cs.keystart = 0;                        Cs.valuestart = 0;                        Cs.setdicvalue = true;                    return true;                    }//Cs.iserror =!cs.jsonstart && cs.state = = 0;                #endregion break; Case ' [': #region EnclosedNumber starts if (!cs.jsonstart) {Cs.arraystart = true;                    return true; } else if (cs.jsonstart && cs.state = = 1) {Cs.childr                        Enstart = true;                    return true;                } #endregion break; Case ': #region brackets End If (cs.arraystart &&!cs.jsonstart && Cs.key                    Start <= 2 && cs.valuestart <= 0)//[{},333]//this end.                        {Cs.keystart = 0;                        Cs.valuestart = 0;                        Cs.arraystart = false;                    return true;                } #endregion break; Case ' ': Case ' \ ': #region quotation marks if (Cs.jsonstart | | Cs. Arraystart) {if (cs.state = = 0)//key stage, possibly array ["AA", {}] {if (cs.keystart <= 0) {Cs.keyst Art = (c = = ' "'?                                3:2);                            return true; } else if ((Cs.keystart = = 2 && c = = ' \ ') | |                            (Cs.keystart = = 3 && c = = ' ")) {if (!cs.escapechar) {C                                    S.keystart =-1;                                return true; } else {Cs.escapechar =                                False }}} else if (cs.state = = 1 && cs.jsonst ART)//value stage must beIt's JSON started. {if (cs.valuestart <= 0) {Cs.val Uestart = (c = = ' "'?                                3:2);                            return true; } else if ((Cs.valuestart = = 2 && c = = ' \ ') | |                            (Cs.valuestart = = 3 && c = = ' ")) {if (!cs.escapechar) {C                                    S.valuestart =-1;                                return true; } else {Cs.escapechar =                                False                    }}} #endregion                Break Case ': ': #region Colon if (cS.jsonstart && Cs.keystart < 2 && Cs.valuestart < 2 && cs.state = = 0) {                        if (Cs.keystart = = 1) {Cs.keystart =-1;                        } cs.state = 1;                    return true; }//Cs.iserror =!cs.jsonstart | |                    (Cs.keystart < 2 && Cs.valuestart < 2 && cs.state = 1);                #endregion break;                        Case ', ': #region comma//["AA", {aa:12,}] if (Cs.jsonstart) {                             if (Cs.keystart < 2 && Cs.valuestart < 2 && cs.state = 1) {                            cs.state = 0;                            Cs.keystart = 0;                            Cs.valuestart = 0;               if (Cs.valuestart = = 1)             {//Cs.valuestart = 0;                            } Cs.setdicvalue = true;                        return true;                        }} else if (Cs.arraystart && cs.keystart <= 2) {                        Cs.keystart = 0;                        if (Cs.keystart = = 1)//{//Cs.keystart =-1;                    } return true;                } #endregion break; Case ': Case ' \ r ': Case ' \ n '://["a", \r\n{}] case ' + ': CAs                    E ' \ t ': if (cs.keystart <= 0 && cs.valuestart <= 0)//cs.jsonstart &&                    {return true;//skips a space.          } break;      Default://value begins with.                            if (c = = ' \ \ ')//Escape symbol {if (Cs.escapechar) {                        Cs.escapechar = false;                            } else {Cs.escapechar = true;                        return true;                    }} else {Cs.escapechar = false;                    } if (Cs.jsonstart | | cs.arraystart)//Json or array begins.                            {if (cs.keystart <= 0 && cs.state = = 0) { Cs.keystart = 1;//without quotation marks} else if (cs.valuestart <= 0 && CS.S                        Tate = = 1 && cs.jsonstart)//Only JSON starts with a value.               {cs.valuestart = 1;//without quotation marks         }} break;        } return false; }    }}


This is how C # recognizes that a string is a JSON-formatted content, and more about topic.alibabacloud.com (www.php.cn)!

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.