从json读取特定数据

时间:2017-05-23 10:13:12

标签: c# arrays json

{"Message":"The request is invalid.","ModelState":{"user.FirstName":["The FirstName field is required."]}}

如何从here.eg读取错误消息.c#中的FirstName字段是必需的。

4 个答案:

答案 0 :(得分:1)

创建特定的类以反序列化您的Json结构。

但这里有一个问题。

  

如果要使用类结构反序列化,则需要   更改" user.FirstName"的属性to" user_FirstName"内   你的json结构,因为在c#variable / property里面你不能   定义"。"

我已经更改了该属性" user.FirstName" to" user_FirstName"在你的json中定义了类

public class ModelState
{
    public IList<string> user_FirstName{ get; set; }
}

public class Example
{
    public string Message { get; set; }
    public ModelState ModelState { get; set; }
}

然后您可以使用以下代码反序列化

    class Program
{
    static void Main(string[] args)
    {
        string jsonstring = @"{ ""Message"":""The request is invalid."",""ModelState"":{ ""user_FirstName"":[""The FirstName field is required.""] }}";
        var serializer = new JavaScriptSerializer();
        var jsonObject = serializer.Deserialize<Example>(jsonstring);
        Console.WriteLine("Error Message : " + jsonObject.Message);
        Console.WriteLine("Error Message : " + jsonObject.ModelState.user_FirstName);
        Console.Read();
    }
}

using System.Web.Script.Serialization;添加到您的命名空间列表中,为此您应该引用&#34; System.Web.Extensions&#34;

答案 1 :(得分:1)

您可以创建一个用于反序列化响应消息的类:

public class Response
{
    public string Message { get; set; }
    public Dictionary<string, string[]> ModelState { get; set; }
}

然后使用像Newtonsoft这样的库:

var response = JsonConvert.DeserializeObject<Response>(jsonString);    
string[] errors = response.ModelState["user.FirstName"];

或更安全的方法 - 在阅读错误之前检查响应消息和属性名称:

var response = JsonConvert.DeserializeObject<Response>(jsonString);
if (response.Message == "The request is invalid.")
{
    string[] errors;
    if (response.ModelState.TryGetValue("user.FirstName", out errors))
    {
        // use errors here
    }
}

答案 2 :(得分:0)

首先将JSON字符串解析为对象var validation = JSON.parse(message) 然后,您可以访问Message和ModelState validation.Message等...

答案 3 :(得分:0)

        try
        {

            string myparameters = "&Address=" + m.Address + "&Address2=" + m.Address2 + "&ContactNumber=" + m.ContactNumber + "&ContactPerson=" + m.ContactPerson + "&Designation=" + m.Designation + "&EmailId=" + m.EmailId + "&Pincode=" + m.Pincode;
            client.Headers["Content-type"] = "application/x-www-form-urlencoded";
            string htmlresult = client.UploadString(posturl, "POST", myparameters);
            Console.WriteLine(htmlresult);
        }
        catch (WebException e)
        {
            using (WebResponse response = e.Response)
            {
                HttpWebResponse httpResponse = (HttpWebResponse)response;
                Console.WriteLine("\nError code: {0}", httpResponse.StatusCode);
                using (Stream data = response.GetResponseStream())
                using (var readerr = new StreamReader(data))
                {
                    string text = readerr.ReadToEnd();
                    Console.WriteLine(text);
                }
            }
        }