简体   繁体   English

如何从此Json获取文本(使用Json.net JObject)

[英]How to Get Text From this Json (Using Json.net JObject)

I have this json 我有这个json

{
  "Message": "The request is invalid.",
  "ModelState": {
    "UserExists": [
      "userName already exists in db."
    ]
  }
}

I can trying to loop through all the model state errors(in this case only 1 but there could be more) 我可以尝试遍历所有模型状态错误(在这种情况下,只有1个,但可能还会更多)

but I can't figure out how to get the text out. 但我不知道如何把文字讲出来。

 JObject o = JObject.Parse(response.Content);
                        var errors = o["ModelState"];
                        foreach (var error in errors)
                        {

                        }

The ModelState you are getting is an object with a property called UserExists which then has an array of error strings. 您得到的ModelState是一个对象,该对象具有名为UserExists的属性,然后具有错误字符串数组。

So you first have to iterate all the properties of the ModelState and then all the values within the array. 因此,您首先必须迭代ModelState所有属性,然后迭代数组中的所有值。

var response = "{\"Message\": \"The request is invalid.\", \"ModelState\": { \"UserExists\": [ \"userName already exists in db.\" ], \"SomeOtherError\": [ \"another error.\", \"two in 1\" ] } }";
var o = JObject.Parse(response);
var errors = o["ModelState"];
foreach (var errorProperty in errors.OfType<JProperty>())
{
    foreach (var error in errorProperty.Values())
    {
        Console.WriteLine("{0}={1}", errorProperty.Name, error);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM