Reputation: 639
I have JSON data that looks like this:
{"AE":{"amount":"0.00000000","value":"0.00000000"},
"AR":{"amount":"0.00000000","value":"0.00000000"},
"BC":{"amount":"0.09670332","value":"3.74814004"}}
And a class that looks like this:
internal class Balance {
internal float amount;
internal float value;
}
I'm trying to read it in with:
private static List<Balance> Balances = new List<Balances>();
Balances = JsonConvert.DeserializeObject<List<Balance>>(json);
... but I'm not really interested in the names of the objects (AE, AR, BC etc). How should I deserialize the input to either discard these names or stuff them someplace?
Upvotes: 0
Views: 666
Reputation: 11364
You can parse the json and iterate over the parent properties. Take the Balance and ignore the property name.
var obj = JObject.Parse(json);
List<Balance> balances = new List<Balance>();
foreach (var item in obj.Properties())
balances.Add(JsonConvert.DeserializeObject<Balance>(obj[item.Name].ToString()));
In essence, you are taking the json under the parent properties (AE, AR, BC) and adding the Balance object (by deserializing it) to the list you want.
obj[item.Name].ToString()
gives you the inner string for each AE, AR, BC etcJsonConvert.Deserialize
converts that string to your Balance classIssues with your Balance Class
Another thing i noticed, you are not using getter and setter
. Without the getter and setter, you wont be able to get any values.
Also, naming convention dictates the variable names start with a capital letter. You can use JsonProperty to define the names that would be in the json.
internal class Balance
{
[JsonProperty("amount")]
public float Amount { get; set; }
[JsonProperty("value")]
public float Value { get; set; }
}
Upvotes: 2
Reputation: 3967
Your json contains a Dictionary<string, Balance>
.
If you just want to extract all the values, use this:
Balances = JsonConvert.DeserializeObject<Dictionary<string, Balance>>(json).Values.ToList();
This will deserialize into the Dictionary<string, Balance>
and then get the List<Balance>
with the values you're looking for.
Upvotes: 2