Reputation: 5209
I am consuming wcf rest service which is returning json as output.
{
"VerifyEmailResult":{
"EmailQueryResult":{
"query":{
"count":1,
"created":"2014-04-23T08:38:04Z",
"email":"test12%40yahoo.com",
"lang":"en-US",
"queryType":"EmailAgeVerification",
"responseCount":0,
"results":[
]
},
"responseStatus":{
"description":"Authentication Error: The signature doesn’t match or the user\/consumer key file wasn’t found.",
"errorCode":3001,
"status":"failed"
}
},
"Message":"Error occurred",
"ResponseMessage":"Failure",
"ResultCode":"0"
}
}
How can I deserialize the same. I don't have any class for json response.
I have to read json and to display some data from json.
Thanks
Upvotes: 1
Views: 4204
Reputation: 11062
How can I deserialize the same. I don't have any class for json response.
If you don't have classes for json string, You can deserialize to dynamic object at runtime.
Example:
dynamic Jsonobject = JsonConvert.DeserializeObject<dynamic>(json);
Console.WriteLine(Jsonobject.VerifyEmailResult.EmailQueryResult.query.email);
Console.WriteLine(Jsonobject.VerifyEmailResult.EmailQueryResult.query["lang"]);
Output:
en-US
Upvotes: 2
Reputation: 62498
Here are your classes:
public class Query
{
public int count { get; set; }
public string created { get; set; }
public string email { get; set; }
public string lang { get; set; }
public string queryType { get; set; }
public int responseCount { get; set; }
public List<object> results { get; set; }
}
public class ResponseStatus
{
public string description { get; set; }
public int errorCode { get; set; }
public string status { get; set; }
}
public class EmailQueryResult
{
public Query query { get; set; }
public ResponseStatus responseStatus { get; set; }
}
public class VerifyEmailResult
{
public EmailQueryResult EmailQueryResult { get; set; }
public string Message { get; set; }
public string ResponseMessage { get; set; }
public string ResultCode { get; set; }
}
public class RootObject
{
public VerifyEmailResult VerifyEmailResult { get; set; }
}
you can use JSON2Csharp.com to get generated classes for you Json in C#.
Use Newton Soft Json library to Deserialize json.
you can Deserialise using this method of library:
StreamReader reader = new StreamReader(response.GetResponseStream());
string json = reader.ReadToEnd();
var Jsonobject = JsonConvert.DeserializeObject<RootObject>(json);// pass your string json here
VerifyEmailResult result = Jsonobject.VerifyEmailResult ;
In my case i was sending a web request to a Restful service and json was returning as string.
Upvotes: 4