Search code examples
c#jsonassert

Extract value for key from json c#


I have the following Json (is a file attached to the project):

{
  "Errors": {
    "NoCountry": {
      "MSG": "The CountryCode field is required.",
      "Description": "Error encountered when Country parameter is missing from the request"
    },
    "NoLOI": {
      "MSG": "Validation failed: \r\n -- LengthOfInterview cannot be empty"
      "Description": "Error encountered when LOI parameter is missing from the request"
    }
  }
}

I need to extract the values for e.g. Errors.NoCompletes.MSG in order to use it in an assert to compare it with an output that i get from the API. Till now i tried to create a dictionary that looks like this:

public class ErrorsDictionary
{
  public string MSG;
  public string Description;
}

public class DicRoot
{
    public Dictionary<string, ErrorsDictionary> Errors { set; get; }
}

And use it like this:

DicRoot Json = JsonConvert.DeserializeObject<DicRoot>(File.ReadAllText(@"c:\users\banu_\source\repos\TestJsonLib\TestJsonLib\Json\ErrorMSG.json"));
foreach (var f in Json.Errors)
{
    Console.WriteLine("Nume={0} Mesaj={1} Description={2}",f.Key, f.Value.MSG, f.Value.Description);
}

The problem is that i cannot figure out, how can i extract a specific value, like what i said above for Errors.NoLOI.MSG, in order to be able to use it in an assert like Assert.Equals(ex, MyParam);


Solution

  • I think what you are asking for is this?

    DicRoot dict = JsonConvert.DeserializeObject<DicRoot>(File.ReadAllText("foo.json"));
    string msg = dict["NoLOI"].MSG;