问题
When I am sending request for a certain API, they return me a json which is awesome, but the problem is that depending on the parameters I provide, the object name is always different while the data structure remains the same. So I am trying to convert the json to a C# class using Newtonsoft library. The only way I've found to do this is by using JsonTextReader, but I'm wondering if there is a cleaner way of achieving this, I looked up the documentation and couldn't find anything to help me in that regard. I also tried using JValue.Parse for dynamic object mapping, but since the property name is always different, it doesn't help me. Here is a code sample to illustrate the problem:
{
"error": [],
"result": {
//This property name always changes
"changingPropertyName": [
[
"456.69900",
"0.03196000",
1461780019.8014,
]]
}
//C# mapping
public partial class Data
{
[JsonProperty("error")]
public object[] Error { get; set; }
[JsonProperty("result")]
public Result Result { get; set; }
}
public class Result
{
[JsonProperty("changingPropertyName")]
public object[][] changingPropertyName{ get; set; }
}
回答1:
One way to deal with a variable property name is to use a Dictionary<string, T>
in place of a strongly typed class (where T
is the type of the variable property you trying to capture). For example:
public partial class Data
{
[JsonProperty("error")]
public object[] Error { get; set; }
[JsonProperty("result")]
public Dictionary<string, object[][]> Result { get; set; }
}
You can then get the first KeyValuePair
from the dictionary and you will have both the name of the variable property and the value available from that.
string json = @"
{
""error"": [],
""result"": {
""changingPropertyName"": [
[
""456.69900"",
""0.03196000"",
1461780019.8014
]
]
}
}";
var data = JsonConvert.DeserializeObject<Data>(json);
KeyValuePair<string, object[][]> pair = data.Result.First();
Console.WriteLine(pair.Key + ":");
object[][] outerArray = pair.Value;
foreach (var innerArray in outerArray)
{
foreach (var item in innerArray)
{
Console.WriteLine(item);
}
}
Fiddle: https://dotnetfiddle.net/rlNKgw
回答2:
You can deserialize it to a c# dynamic using:
dynamic dynamicObj= JsonConvert.DeserializeObject<dynamic>(jsonResultString);
来源:https://stackoverflow.com/questions/36923920/deserialize-dynamic-object-name-for-newtonsoft-property