Search code examples
c#javascriptserializer

Parsing Json information from a Json file as a string


I am looking for some help with regards to Parsing the the value "mppdemo" in the below json file (See screenshot)

{
   "client":{
     "isWebLogin":false,
     "registryName": "mpdemo",
     "walletCode": "Local"
   }
}

I have done some research in and arround the webs but alot of the examples wither are out dated or dont work.

This is what i have tried

//JObject T = JObject.Parse(File.ReadAllText(DownloadConfigFilelocation));
var source = File.ReadAllText(DownloadConfigFilelocation);
var JavaScriptSerializer MySerializer = new JavaScriptSerializer();
var myObj = MySerializer.Deserialize<T>(source);
var RegistryName = myObj.searchResults[0].hotelID;

MessageBox.Show(RegistryName);

The above doesnt pick up the JavaScriptSerializer function from the library even though im using the using System.Web.Script.Serialization;

Can someone help me get this code segment to work I hope i have provided enough info


Solution

  • EDIT: I just realized that you're having another problem - that your compiler does not recognize the System.Web.Script.Serialization.JavaScriptSerializer type. You'll need to add a reference to System.Web.Extensions.dll to your project. I don't know what IDE you are using, but for example in SharpDevelop you can right click References > Add Reference > in filter start typing "System.Web.Extensions" > among results find "System.Web.Extensions" and double click it (it will be moved to lower window) > hit OK and compile your project.

    enter image description here

    If you still want to use System.Web.Script.Serialization.JavaScriptSerializer, I'd probably do it like this:

    using System;
    using System.Text.RegularExpressions;
    using System.Web.Script.Serialization;
    
    namespace jsonhratky
    {
        public static class Program {
    
            public static void Main(string[] args)
            {
                var instance = new JsonParsingTest();
            }
        }
    
        public class JsonParsingTest
        {
            class Response {
                public Client client;
            }
    
            class Client {
                public bool isWebLogin;
                public string registryName;
                public string walletCode;
            }
    
            const string JSON_EXAMPLE = ("{" + ("\"client\":{" + ("\"isWebLogin\":false," + ("\"registryName\": \"mpdemo\"," + ("\"walletCode\": \"Local\"" + ("}" + "}"))))));
    
            public JsonParsingTest() {
                // Solution #1 using JavaScriptSerializer
                var serializer = new JavaScriptSerializer();
                Response parsed = serializer.Deserialize<Response>(JSON_EXAMPLE);
                Console.WriteLine("parsed isWebLogin: " + parsed.client.isWebLogin);
                Console.WriteLine("parsed registryName: " + parsed.client.registryName);
                Console.WriteLine("parsed walletCode: " + parsed.client.walletCode);
    
                // Solution #2 (not recommended)
                var matches = Regex.Match(JSON_EXAMPLE, "registryName\":.*?\"([^\"]+)\"", RegexOptions.Multiline);
                if (matches.Success) {
                    Console.WriteLine("registryName parsed using Regex: " + matches.Groups[1].Value);
                } else {
                    Console.WriteLine("Solution using Regex failed.");
                }
    
                Console.WriteLine("Press any key to continue...");
                Console.ReadKey();
            }
        }
    }
    

    You need to create a "POJO" class (there's probably another term in C# for plain old classes) with fields matching those in your string response. Since your fields isWebLogin, registryName and walletCode are not directly part of main object (Response) but they belong to sub-class (Client), you need two classes: Response (or call it whatever you want) and then the field "client" must match string in response (as well as the fields of the sub-class).

    Result:

    parsed json - running program

    Anyway, I also included a solution using Regex, but I absolutely don't recommend that. It's suitable only as a workaround and only then if you know that your response will never contain more than one "client" objects.