Extract value for key from json c#
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: rn -- 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:usersbanu_sourcereposTestJsonLibTestJsonLibJsonErrorMSG.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);
I'm under the impression that a closing double quotation mark is missing for the value of the scond MSG ?
– Ole EH Dufour
Jul 1 at 10:28
I think also the comma is missing after that @OleEHDufour noticed
– L_J
Jul 1 at 11:12
It's not clear to me what you're asking. If you've got a dictionary and you know the key you want to look up, just use
TryGetValue or the indexer.– Daisy Shipton
Jul 1 at 11:30
TryGetValue
4 Answers
4
I think what you are asking for is this?
DicRoot dict = JsonConvert.DeserializeObject<DicRoot>(File.ReadAllText("foo.json"));
string msg = dict["NoLOI"].MSG;
This is exactly what i needed, only mention is that it should be: string msg = dict.Errors["NoLOI"].MSG;
– Banu
Jul 1 at 19:19
You can also use JsonPath, anonymous types and string interpolation if you like:
JObject obj = JObject.Parse(json);
var errors = obj
.SelectTokens("$.Errors.*")
.ToDictionary(
e => ((JProperty)e.Parent).Name,
e => new { Msg = e["MSG"], Descr = e["Description"] });
foreach (var e in errors)
{
Console.WriteLine($"Nume={e.Key} Mesaj={e.Value.Msg} Description={e.Value.Descr}");
}
I know this looks like a bit working around. However, it's working.
class Program
{
static void Main(string args)
{
string json = "{"Errors": {"NoCountry": {"MSG": "The CountryCode field is required.","Description": "Error encountered when Country parameter is missing from the request"},"NoLOI": {"MSG": "Validation failed: rn -- LengthOfInterview cannot be empty", "Description": "Error encountered when LOI parameter is missing from the request"},}}";
var Json = JsonConvert.DeserializeObject<ErrorsClass>(json);
var obj = JsonConvert.DeserializeObject<Dictionary<string, ErrorsDictionary>>(Json.Errors.ToString());
foreach (var f in obj)
{
Console.WriteLine("Nume={0} Mesaj={1} Description={2}", f.Key, f.Value.MSG, f.Value.Description);
}
Console.Read();
}
}
public class ErrorsDictionary
{
public string MSG { get; set; }
public string Description { get; set; }
}
public class DicRoot
{
public Dictionary<string, ErrorsDictionary> ErrorsDic { set; get; }
}
class ErrorsClass
{
public object Errors { get; set; }
}
Output:
Nume=NoCountry Mesaj=The CountryCode field is required. Description=Error encountered when Country parameter is missing from the request
Nume=NoLOI Mesaj=Validation failed:
-- LengthOfInterview cannot be empty Description=Error encountered when LOI parameter is missing from the request
Nume=NoCountry Mesaj=The CountryCode field is required. Description=Error encountered when Country parameter is missing from the request
Nume=NoLOI Mesaj=Validation failed:
-- LengthOfInterview cannot be empty Description=Error encountered when LOI parameter is missing from the request
You can use Newtonsoft.json NuGet. Try this
var files = JObject.Parse(YourJson);
var recList = files.SelectTokens("$..Errors").ToList();
foreach (JProperty prop in recList.Children())
{
string key = prop.Name.ToString();
string value = prop.Value.ToString();
//Do your stuffs here
}
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Start with stackoverflow.com/a/48023576/4180382
– Ole EH Dufour
Jul 1 at 10:22