Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I read each filed of json

Tags:

json

c#

json.net

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.

like image 759
S.D.H.Z Avatar asked Dec 20 '25 15:12

S.D.H.Z


2 Answers

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);
}
like image 111
Mohit S Avatar answered Dec 23 '25 06:12

Mohit S


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;
like image 36
vojta Avatar answered Dec 23 '25 07:12

vojta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!