Reputation: 57
I am posting to API and get a response
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
var jsonResponse = JsonConvert.SerializeObject(responseString , Formatting.Indented);
and this is the value of jsonResponse :
"{\"Id\":333,
\"Name\":\"TestProduct\",
\"ApplicationId\":\"9edcc30d-7852-4c95-a6b2-1bf370655965\",
\"Features\":[{
\"Id\":301,
\"Name\":\"Sodalis Mobile Client2.0\",
\"Code\":\"Beeware.Sodalis.Mobile\",
\"ProductId\":0,
\"Selected\":null}]
}"
how can I read each filed ?
like Name , ApplicationId , Features-Name and Features-Code.
I would appreciate any help.
Upvotes: 3
Views: 97
Reputation: 172
Try this classes
public class MyResponse
{
public int Id { get; set; }
public string Name { get; set; }
public string ApplicationID { get; set; }
public List<MyFeature> Features { get; set; }
}
public class MyFeature
{
public int Id { get; set; }
public string Name { get; set; }
public string Code { get; set; }
public int ProductId { get; set; }
public bool? Selected { get; set; }
}
then you can read json by this
string _Json = @"{'Id':333,'Name':'TestProduct','ApplicationId':'9edcc30d-7852-4c95-a6b2-1bf370655965','Features':[{'Id':301,'Name':'Sodalis Mobile Client2.0','Code':'Beeware.Sodalis.Mobile','ProductId':0,'Selected':null}]}";
MyResponse M = JsonConvert.DeserializeObject<MyResponse>(_Json);
Upvotes: 1
Reputation: 14064
You have to create a class like
public class Feature
{
[JsonProperty("Id")]
public int Id { get; set; }
[JsonProperty("Name")]
public string Name { get; set; }
[JsonProperty("Code")]
public string Code { get; set; }
[JsonProperty("ProductId")]
public int ProductId { get; set; }
[JsonProperty("Selected")]
public object Selected { get; set; }
}
public class YourApp
{
[JsonProperty("Id")]
public int Id { get; set; }
[JsonProperty("Name")]
public string Name { get; set; }
[JsonProperty("ApplicationId")]
public string ApplicationId { get; set; }
[JsonProperty("Features")]
public IList<Feature> Features { get; set; }
}
then to Deserialize it just do
YourApp p = JsonConvert.DeserializeObject<YourApp>(json);
Console.WriteLine(p.Name + p.ApplicationId);
You can read all the features by using a foreach since now all the feautures are there in your object
foreach(Feature AllFeatures in p.Features)
{
Console.WriteLine(AllFeatures.Name + AllFeatures.Code);
}
Upvotes: 2
Reputation: 5661
First of all, create classes which will hold your response:
public class MyResponse {
public int Id {get; set;}
public string Name {get; set;}
public string ApplicationID {get; set;}
public IList<MyFeature> Features {get; set;}
}
public class MyFeature {
public int Id {get; set;}
public string Name {get; set;}
public int ProductId {get; set;}
public string Selected {get; set;}
}
Then you can use JsonConvert
:
MyResponse response = JsonConvert.DeserializeObject<MyResponse>(responseString);
string name = response.Name;
Upvotes: 1