Try creating an object to serialize to and use the JsonProperty attribute to map the json properties to the C# properties:
public class RealtimeCurrencyExchangeRate
{
[JsonProperty("1. From_Currency Code")]
public string CurrencyCode { get; set; }
}
Then use the correct type when deserializing.
var obj = JsonConvert.DeserializeObject<RealtimeCurrencyExchangeRate >(json);
References:
Spaces handling: Deserializing JSON when fieldnames contain spaces
DeserializeObject: https://www.newtonsoft.com/json/help/html/DeserializeObject.htm
Or, if you want to dynamically read the properties, you can create a custom contract resolver:
public class AlphaVantageApiContractResolver : DefaultContractResolver
{
protected override string ResolvePropertyName(string propertyName)
{
// derive the C#property name from the JSON property name
var cSharpPropertyName = propertyName;
// Remove all periods from the C#property name
cSharpPropertyName = cSharpPropertyName.Replace(".", "");
// replace all spaces with underscores
cSharpPropertyName = cSharpPropertyName .Replace(" ", "_");
// The value you return should map to the exact C# property name in your class so you need to create classes to map to.
return cSharpPropertyName;
}
}
and use this while deserializing:
var jsonSettings = new JsonSerializerSettings();
jsonSettings.ContractResolver = new AlphaVantageApiContractResolver();
var obj = JsonConvert.DeserializeObject<MyClass>(json, jsonSettings);
https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Serialization_DefaultContractResolver.htm#!
You will still have to create classes that map to the objects but now you don't have to worry about the JsonProperty attribute on every property. Just remember to remove periods and replace spaces with underscores in your C# property names. You will also have to write some code to remove numbers at the beginning of property names because this isn't allowed in C#.
If you can't pre-define your classes, you will need to deserialize anonymous objects and work with that.
.notation vs brackets to access the object data.