Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting values from Json.net

Tags:

json.net

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,

like image 550
Roger Avatar asked Apr 10 '11 22:04

Roger


1 Answers

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);                
}
like image 189
David Hall Avatar answered Oct 11 '22 13:10

David Hall