I want to convert this Json to list in c#.
Here's my JSON string and class
{"Headers":[{"KeyValue":"Hello AA"},{"KeyValue":"Hello BB"}],"Footers":[{"KeyValue":"Wifi Password : 11112222"}]}
public class Template
{
public List<HeaderInfo> Headers { get; set; }
public List<FooterInfo> Footers { get; set; }
}
public class HeaderInfo
{
public string KeyValue { get;set; }
}
public class FooterInfo
{
public string KeyValue { get; set; }
}
When I try convert it , it shows this problem:
Cannot deserialize the current JSON object (e.g.
{"name":"value"}
) into typeSystem.Collections.Generic.List<DXClass.Model.Template>
because the type requires a JSON array (e.g.[1,2,3]
) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. Path 'Headers', line 1, position 11.'
CodePudding user response:
Your JSON string is not a list but a single object. When you'd call JsonConvert.DeserializeObject<Template>
the deserialization will succeed.
If you expect it to be a list, the JSON would look like this:
[{"Headers":[{"KeyValue":"Hello AA"},{"KeyValue":"Hello BB"}],"Footers":[{"KeyValue":"Wifi Password : 11112222"}]}]
CodePudding user response:
you are doing it incorrectly, your equivalent of JSON is Template
object, not the List<Template>
. It should be like this Template template = JsonConvert.DeserializeObject<Template>(inoutJson);