1

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

Liam
  • 27,717
  • 28
  • 128
  • 190
GrahamNorton
  • 121
  • 1
  • 8
  • Is there a particular reason you are using `JavaScriptSerializer` vs JSON,NET ? – mjwills Jul 19 '18 at 08:11
  • 1
    `var JavaScriptSerializer MySerializer` isn't the correct way to declare a variable. Either implicitly type the variable (`var MySerializer`) or explicitly type it (`JavaScriptSerializer MySerializer`). The [documentation](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/var) has more info on the use of `var`. – Diado Jul 19 '18 at 08:12
  • 5
    Possible duplicate of [How can I parse JSON with C#?](https://stackoverflow.com/questions/6620165/how-can-i-parse-json-with-c) – Liam Jul 19 '18 at 08:14

2 Answers2

1

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.

0

The problem seems to be in this line of your code var myObj = MySerializer.Deserialize<T>(source); You need to give the type of object instead of T.

Tabby
  • 91
  • 1
  • 1
  • 10