What are the ideas of using C-sharp to write a method to parse a simple JSON string?

I didn"t find an easy way to parse JSON strings in the .NET Framework. There is something like Newtonsoft.Json, but it"s too heavy, so I want to build my own wheel.

for the following simple JSON string:

{
   "error": {
      "code": "request_token_invalid", 
      "message": "The access token isn"t valid."
   }
}

given a method, pass in a string and key, and return the corresponding value.

public static string JsonToValue(string json,string key) {
    // Todo
}

my idea is to iterate through the strings, find the locations of all the double quotes, and then take them out and put them in the list, and the string after key is the value you are looking for.

public static string JsonToValue(string json,string key) {
    var index = new List<int>();
    for (int i = 0; i < json.Length; iPP) {
        if (json[i] == """) index.Add(i);
    }
    var str = new List<string>();
    for (int i = 0; i < index.Count; iPP) {
        str.Add(json.Substring(index[i] + 1,index[i + 1] - index[i] - 1));
        iPP;
    }
    for (int i = 0; i < str.Count; iPP) {
        if (str[i] == key) return str[i + 1];
    }
    return null;
}

but this method is too tedious, do you have any better ideas?

Apr.06,2021

built-in approach: serialization and deserialization of objects using the JavaScriptSerializer class under the System.Web.Script.Serialization namespace provided in .NET Framework 3.5 / 4.0 is straightforward.

Project p = new Project() { Input = "stone", Output = "gold" };
 JavaScriptSerializer serializer = new JavaScriptSerializer();
 var json = serializer.Serialize(p);
 Console.WriteLine(json);

 var p1 = serializer.Deserialize<Project>(json);
 Console.WriteLine(p1.Input + "=>" + p1.Output);
 Console.WriteLine(ReferenceEquals(p,p1));

contract method: implemented using DataContractJsonSerializer or JsonReaderWriterFactory provided by System.Runtime.Serialization.dll.

Project p = new Project() { Input = "stone", Output = "gold" };
DataContractJsonSerializer serializer = new DataContractJsonSerializer(p.GetType());
string jsonText;

using (MemoryStream stream = new MemoryStream())
{
    serializer.WriteObject(stream, p);
    jsonText = Encoding.UTF8.GetString(stream.ToArray());
    Console.WriteLine(jsonText);
}

using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonText)))
{
    DataContractJsonSerializer serializer1 = new DataContractJsonSerializer(typeof(Project));
    Project p1 = (Project)serializer1.ReadObject(ms);
    Console.WriteLine(p1.Input + "=>" + p1.Output);
}

is the compilation principle. First, lexical analysis is done with regular expressions, and then top-down / bottom-up syntax analysis. Although it is a bit of a killer, wheels are built for the purpose of doing something more academic


.
  1. use grammatical parsing. (compilation principle)
  2. use existing wheels.
  3. uses regular expressions.

the first method is slightly more complex and needs to be handled by a class, but it is powerful enough to parse lists and objects.
the second method is feasible, but does not quite meet the requirements of the subject. The third method,
, is simple in structure and requires only one function, but can only parse string key-value pairs. Numbers and Boolean values can be parsed with proper processing.

these three methods are described in more detail below.

the first method

requires a class to represent the parser and two classes to represent the object. The code is slightly longer, with a total of about 300 lines. If the subject needs it, I will post it again.

the second method

Microsoft.Extensions.Configuration.Json , document: Configuration in ASP.NET Core

should be able to meet the demand.

the third method

static void Main(string[] args)
{
    var jsonSegments = new string[]
    {
        "{",
        "  \"a\": {",
        "    \"b\": true",
        "  },",
        "  \"c\": [",
        "    1,",
        "    2",
        "  ]",
        "  \"d\": 1,",
        "  \"e\": \"\\\"Good.\\\", he said.\",",
        "  \'e': 'second e',",
        "  'f': 'get f'",
        "}"
    };
    var json = string.Join(Environment.NewLine, jsonSegments);
    WriteLine(json);
    WriteLine();

    Show(json);
}

static void Show(string json)
{
    foreach (var key in new string[] { "a", "b", "c", "d", "e", "f" })
    {
        WriteLine(key + ": " + (JsonToValue(json, key) ?? "not found."));
    }
}

output:

{
  "a": {
    "b": true
  },
  "c": [
    1,
    2
  ]
  "d": 1,
  "e": "\"Good.\", he said.",
  'e': 'second e',
  'f': 'get f'
}

a: not found.
b: not found.
c: not found.
d: not found.
e: \"Good.\", he said.
f: get f

Summary

using grammatical parsing is more elegant, interesting and powerful. Using regularities is simple, but the process of designing regular matching patterns is lengthy and no faster than grammar parsing. Regular matching is still not appropriate.

I hope to adopt it.

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b3b3f2-4d918.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b3b3f2-4d918.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?