Reputation: 215
I'm trying to make a dictionary of a json values to index them with a string. I'm using Newtonsoft to deserialze json string. my json is :
{
"financialPositions": [
{
"fieldName": "Assets",
"periodEndToDateValue": 0.0,
"pastYearEndToDateValue": 0.0,
"description": "\u062f\u0627\u0631\u0627\u06cc\u06cc\u200c\u200c\u0647\u0627",
"percentChanges": 0.0,
"rowClass": "GroupHeader"
},
{
"rowClass": "ComputationalRow",
"fieldName": "ListedCapital",
"description": "\u0633\u0631\u0645\u0627\u06cc\u0647",
"percentChanges": 0.0,
"currentPeriodEndToDateValue": 1.0,
"pastSimillarEndToDateValue": 1.0,
"pastYearEndToDateValue": 1.0
}
]
}
I used this classes :
public class RootObject
{
public FinancialPositions[] financialPositions{ get; set; }
}
public class FinancialPositions
{
public string fieldName { get; set; }
public double periodEndToDateValue { get; set; }
public double pastYearEndToDateValue { get; set; }
public string description { get; set; }
public float percentChanges { get; set; }
public string rowClass { get; set; }
}
and I use this to deserialize the json string :
RootObject oRootObject = new RootObject();
oRootObject = JsonConvert.DeserializeObject<RootObject>(jsonstring);
what changes need to address them like below?
oRootObject.financialPositions["Assets"]
Upvotes: 0
Views: 72
Reputation: 7204
You can define an indexer []
for your object.
public class RootObject
{
public FinancialPositions[] financialPositions{ get; set; }
public object this[string name]
{
get { return financialPositions.FirstOrDefault(f => f.fieldName == name); }
set { }
}
}
Then call
oRootObject["Assets"]
it returns your object
{
"fieldName": "Assets",
"periodEndToDateValue": 0.0,
"pastYearEndToDateValue": 0.0,
"description": "\u062f\u0627\u0631\u0627\u06cc\u06cc\u200c\u200c\u0647\u0627",
"percentChanges": 0.0,
"rowClass": "GroupHeader"
}
Upvotes: 4