convert from json to c using nested classes including arrays

Your problem is that the JZ_Employee property is an array-valued property that lacks a setter:

public JZ_Employee_[] JZ_Employee { get; } = new JZ_Employee_[10];

Because .Net arrays cannot be resized, Json.NET treats them as read-only collections whose contents need to be accumulated into a temporary list which is then used to construct the array and set it back in its parent. However, your array property has no setter, so Json.NET sees it as completely read-only and skips it entirely.

To resolve this problem, you could add a setter. It could be protected or private if you mark the property with [JsonProperty]:

public JZ_Employee_[] JZ_Employee { get; private set; } = new JZ_Employee_[10];

Demo fiddle #1 here.

Alternatively, you could leave the property as get-only but replace the array with a resizable collection such as List<JZ_Employee_>:

public List<JZ_Employee_> JZ_Employee { get; } = new List<JZ_Employee_>();

Demo fiddle #2 here.

This second option has the advantage that you can apply [JsonConverter(typeof(SingleOrArrayConverter<JZ_Employee_>))] or just [JsonConverter(typeof(SingleOrArrayListConverter))] from the answers to How to handle both a single item and an array for the same property using to JZ_Employee, which will allow you to merge the ResponseJSPG2 and ResponseJSPG2A classes:

public List<JZ_Employee_> JZ_Employee { get; } = new List<JZ_Employee_>();

The converter will automatically convert the case of a single JZ_Employee object into a list with one item.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top