从JSON C#中提取密钥的值

时间:2018-07-01 10:20:05

标签: c# json assert

我有以下Json(是项目附带的文件):

<foos>
    <foo>
        <entry>
            <key name="foo1"/>
            <value  name="foo1"/>
        </entry>
    </part>
    <foo>
        <entry>
            <key name="foo2"/>
            <value  name="foo2"/>
        </entry>
    </part>
</parts>

我需要提取例如为了在断言中使用它以将其与我从API获得的输出进行比较,请使用Errors.NoCompletes.MSG。 直到现在,我一直试图创建一个像这样的字典:

{
  "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"
    }
  }
}

并像这样使用它:

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

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

问题是我无法弄清楚,如何才能提取特定值,就像我上面对Errors.NoLOI.MSG所说的那样,以便能够在Assert.Equals(ex, MyParam);

4 个答案:

答案 0 :(得分:1)

如果愿意,还可以使用JsonPath,匿名类型和字符串插值:

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}");
}

答案 1 :(得分:0)

我想这是您要的吗?

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

答案 2 :(得分:0)

我知道这看起来有些变通。但是,它正在工作。

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: \r\n -- 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; }
}

输出:

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

答案 3 :(得分:0)

您可以使用Newtonsoft.json NuGet。试试这个

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
}