Can you Instantiate an Object Instance from JSON in .NET?

前端 未结 5 1651
一向
一向 2021-01-02 09:20

Since Object Initializers are very similar to JSON, and now there are Anonymous Types in .NET. It would be cool to be able to take a string, such as JSON, and create an Anon

5条回答
  •  Happy的楠姐
    2021-01-02 09:47

    I wrote a relatively short method that will Parse JSON and return a name/value Dictionary that can be accessed similarly to the actual object in JavaScript.

    Here's a sample usage of the below method:

    var obj = ParseJsonToDictionary("{FirstName: \"Chris\", \"Address\":{Street:\"My Street\",Number:123}}");
    
    // Access the Address.Number value
    object streetNumber = ((Dictionary)obj["Address"])["Number"];
    

    And, here's the code for the ParseJsonToDictionary method:

    public static Dictionary ParseJsonToDictionary(string json)
    {
        var d = new Dictionary();
    
        if (json.StartsWith("{"))
        {
            json = json.Remove(0, 1);
            if (json.EndsWith("}"))
                json = json.Substring(0, json.Length - 1);
        }
        json.Trim();
    
        // Parse out Object Properties from JSON
        while (json.Length > 0)
        {
            var beginProp = json.Substring(0, json.IndexOf(':'));
            json = json.Substring(beginProp.Length);
    
            var indexOfComma = json.IndexOf(',');
            string endProp;
            if (indexOfComma > -1)
            {
                endProp = json.Substring(0, indexOfComma);
                json = json.Substring(endProp.Length);
            }
            else
            {
                endProp = json;
                json = string.Empty;
            }
    
            var curlyIndex = endProp.IndexOf('{');
            if (curlyIndex > -1)
            {
                var curlyCount = 1;
                while (endProp.Substring(curlyIndex + 1).IndexOf("{") > -1)
                {
                    curlyCount++;
                    curlyIndex = endProp.Substring(curlyIndex + 1).IndexOf("{");
                }
                while (curlyCount > 0)
                {
                    endProp += json.Substring(0, json.IndexOf('}') + 1);
                    json = json.Remove(0, json.IndexOf('}') + 1);
                    curlyCount--;
                }
            }
    
            json = json.Trim();
            if (json.StartsWith(","))
                json = json.Remove(0, 1);
            json.Trim();
    
    
            // Individual Property (Name/Value Pair) Is Isolated
            var s = (beginProp + endProp).Trim();
    
    
            // Now parse the name/value pair out and put into Dictionary
            var name = s.Substring(0, s.IndexOf(":")).Trim();
            var value = s.Substring(name.Length + 1).Trim();
    
            if (name.StartsWith("\"") && name.EndsWith("\""))
            {
                name = name.Substring(1, name.Length - 2);
            }
    
            double valueNumberCheck;
            if (value.StartsWith("\"") && value.StartsWith("\""))
            {
                // String Value
                d.Add(name, value.Substring(1, value.Length - 2));
            }
            else if (value.StartsWith("{") && value.EndsWith("}"))
            {
                // JSON Value
                d.Add(name, ParseJsonToDictionary(value));
            }
            else if (double.TryParse(value, out valueNumberCheck))
            {
                // Numeric Value
                d.Add(name, valueNumberCheck);
            }
            else
                d.Add(name, value);
        }
    
        return d;
    }
    

    I know this method may be a little rough, and it could probably be optimized quite a bit, but it's the first draft and it just works.

    Also, before you complain about it not using regular expressions, keep in mind that not everyone really understands regular expressions, and writing it that way would make in more difficult for others to fix if needed. Also, I currently don't know regular expression too well, and string parsing was just easier.

提交回复
热议问题