i have the following JSON i´m requesting from a service with C# using Newtonsoft.Json
[
{"Example1":value1,
"Example2":value1,
"Example3":"value1",
"ExampleList":
{"Example4":"",
"Example5":"value1",
"Example6":"value1",
"Example7":"",
"Example8":"value1"},
"Example9":["value1"],
"Example10":[]
}
]
the problem here are the "ExampleList", "Example9" and "Example10". "ExampleList" list has no defined number of values. it can be 5, in the next query it can be 20.
I already have a similar request, where I only have the ExampleList without the values above it. I solved this with
Dictionary<string, string>
and it works fine.
My question is, how can I combine these two?
I tried something like this i found here Parsing JSON with dynamic properties
public partial class ExampleClass
{
public int Example1 { get; set; }
public long Example2 { get; set; }
public long Example3 { get; set; }
public ExampleList exampleList { get; set; }
}
public partial class ExampleList
{
Dictionary<string, string> exampleList = new Dictionary<string, string>();
}
Error:
JsonSerializationException: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Models.ExampleClass' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
Edit: Guru Strons solution worked. For Example 9 and 10 I created an array.
public class ExampleClass
{
public int Example1 { get; set; }
public int Example2 { get; set; }
public int Example3 { get; set; }
public Dictionary<string,string> ExampleList { get; set; }
public string[] Example9 { get; set; }
public string[] Example10 { get; set; }
}
var tempAttr = JsonConvert.DeserializeObject<List<ExampleClass>>(response);
CodePudding user response:
If the goal is to deserialize dynamically only the ExampleList
- there is no need to introduce class for it, just make property of type Dictionary<string, string>()
:
public partial class ExampleClass
{
public int Example1 { get; set; }
public long Example2 { get; set; }
public long Example3 { get; set; }
public Dictionary<string, string>() ExampleList { get; set; }
}
There is another problem - it seems that you are trying to deserialize to ExampleClass
but your root json is array, so use List<ExampleClass>
or another collection type:
JsonConvert.DeserializeObject<List<ExampleClass>>(...);