Click here to Skip to main content
15,878,852 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have tried to get specific value from json data but getting null or exception

The below is my json data

{
  "Name": "Kumar",
  "policyName": "Lic",
  "targetResource": "3Months",
  "attributes": {
    "MajorIssue": {
      "attributeId": 1,
      "attributeKey": "check",
      "attributeValue": "7776000000"
    }
  },
  "enabled": true
}


need to get this value from the above json data
"attributeValue": "7776000000"


What I have tried:

The below is my code that i have tried to fetch the specific value

dynamic Result = JsonConvert.DeserializeObject(jsonResultFromAPI);


foreach (var item in Result )
{

    retentionPeriod = item.attributes.attributeValue;//API Value;

}
Posted
Updated 31-Oct-21 16:39pm

I suggest to create models to present your JSON data:
public class MajorIssue
{
    public int attributeId { get; set; }
    public string attributeKey { get; set; }
    public string attributeValue { get; set; }
}

public class Attributes
{
    public MajorIssue MajorIssue { get; set; }
}

public class RootObject
{
    public string Name { get; set; }
    public string policyName { get; set; }
    public string targetResource { get; set; }
    public Attributes attributes { get; set; }
    public bool enabled { get; set; }
}

so you can deserialize objects easily:
dynamic Result = JsonConvert.DeserializeObject<RootObject>(jsonResultFromAPI);

var value = Result.Attributes.MajorIssue.attributeValue;
 
Share this answer
 
Comments
DGKumar 27-Apr-18 17:22pm    
Hi Majdi,

With out taking class can we get that specific value from API response which is in json format
Majdi Saibi 27-Apr-18 17:25pm    
Yes, you can. Without looping through the result object.

var value = Result.attributes.attributeValue;
DGKumar 28-Apr-18 2:56am    
I have a property in json with - symbol like "ren-es-value"
due to that i am not able to get value getting exception.
Result.attributes-List.attributeValue;
I have replace that value without - symbol.
Now it is working thankyou
Majdi Saibi 28-Apr-18 13:21pm    
Awesome! If my answer helped you please mark it as Answer.
Try this plz:
var innerObj = Result.GetType().GetProperty("attributes");
return innerObj.GetType().GetProperty("attributeValue").GetValue(innerObj).ToString();
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900