简体   繁体   中英

How to parse json data in WPF C#?

I want to parse json data. Below is my json response.

{
    "error": true,
    "errors": {
        "email": [
            "Enter a valid email address."
        ]
    }
}

Below is my sample code.

JObject obj = JObject.Parse(res);

string Status = (string)obj["error"];

if (Status == "True" || Status == "true")   
{
    string email = obj["errors"]["email"].ToString();
    MessageBox.Show(email );
    return;
}

but I am getting email value is '["Enter a valid email address."]' .

I want to remove '[]' . How to do this?

Unless your schema is dynamic you're almost always better off going with a type-safe approach ie:

public class Errors
{
    public string[] email { get; set; }
}

public class MyData
{
    public bool error { get; set; }
    public Errors errors { get; set; }
}

And then deserializing like this:

var json = "{\"error\": true, \"errors\": { \"email\": [\"Enter a valid email address.\"]}}";
var data = JsonConvert.DeserializeObject<MyData>(json);

email in the sample json given in OP, is an array. If you need to access all values in the array, you need to loop through each element in the array. For example

foreach(var emailValue in obj["errors"]["email"])
{
string email = (string)emailValue;
// do rest
}

If you only need the first element in the array, you could use

var email = (string)obj["errors"]["email"][0];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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