Newtonsoft catch part of JSON

Asked

Viewed 39 times

1

I’m working with C# and I want to take part of JSON returned by request PostAsync and this is the return of REQUEST:

{"meta":{"status":422,"error":true},"error":{"status":1102,"msg":"Invalid email, enter email in the format [email protected]"}}

I created the following class to check if error is with true or false, but I couldn’t get part of the JSON and associate with the class.

public class Meta
{
    [JsonProperty("meta.status")]
    public string Status { get; set; }

    [JsonProperty("meta.error")]
    public bool Error { get; set; }
}

1 answer

1


That kind of information is in the format JSON to extract the information with the package that is attached to your question you need to have a set of classes, following the example below:

public class Rootobject
{
    public Meta meta { get; set; }
    public Error error { get; set; }
}

public class Meta
{
    public int status { get; set; }
    public bool error { get; set; }
}

public class Error
{
    public int status { get; set; }
    public string msg { get; set; }
}

Code

var json = "{ ... }";
var result = Newtonsoft
            .Json
            .JsonConvert
            .DeserializeObject<Rootobject>(json);

result.meta.status // status
result.meta.error // error

You can also decorate the same object as you did, but, is every item in the setting must be respected.

  • 1

    Grateful @Virgilio Novic, tested and worked

Browser other questions tagged

You are not signed in. Login or sign up in order to post.