10

I have a situation where I will get some known values from an api in json, but then need to get to a set of unknown values (for instance the password and email error in this json):

{"error":{"httpCode":400,"message":"Invalid parameters"},  "message":{"errors":
    {"password":"is too short"
    ,"email":"is invalid"}}}

I know I will always get 'error' and 'message.errors'. I do not know ahead of time what the tokens/properties will be (password, email)

I am trying to use Json.net to get at them, and just write to a string builder: "password is too short, email is invalid"

 JObject root = JObject.Parse(<json string>);

that code gives me root.Properties, but I am doing something wrong, as I don't get properties off it's children. What don't I get?

Thanks,

1 Answer 1

13

There may well be a better way to do this, but the following code worked for me to extract the key and value of the key pairs within the errors array:

string data =
    @"{""error"":{""httpCode"":400,""message"":""Invalid parameters""},  ""message"":{""errors"": 
    {""password"":""is too short"" 
    ,""email"":""is invalid""}}}";

JObject jObject = JObject.Parse(data);

JObject errors = (JObject)jObject["message"]["errors"];

foreach(var error in errors)
{
    MessageBox.Show(p.Key + p.Value);                
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.