Reputation: 3500
I am working on a C# project.
[
{"FirstName":"XYZ","LastName":"SSS"},
{"FirstName":"ABC","LastName":"NNN"}
]
Each row represents an object of class ChildDTO.
I read the above data from the file and am trying to deserialize into a ParentCollection object like below:
string file = System.IO.File.ReadAllText("Children_CA.txt");
ParentCollection pCollection = Newtonsoft.Json.JsonConvert.DeserializeObject<ParentCollection>(file);
My DTO classes are like below:
[Serializable]
public class ParentCollection : CollectionBase
{
public void Add(ChildDTO dto)
{
//List is from Systems.Collections.CollectionBase class
List.Add(dto);
}
}
[Serializable]
public class ChildDTO
{
// properties like FirstName and LastName goes here
}
I cannot change my DTO classes since they are old and already in production from the past 20 years and many applications are using them.
When I see Quick Watch on pCollection, I notice the collection is having objects of type Newtonsoft.Json.Linq.JObject. I am hoping to have objects of type ChildDTO
Please let me know what mistake I am doing.
Upvotes: 2
Views: 1620
Reputation: 129667
The problem is that CollectionBase
, and by extension your ParentCollection
class, are not generic, so Json.Net doesn't know that the items in the collection are supposed to be ChildDTO
objects. Since it doesn't know what type the items are, it just uses JObject
instead. You can fix the problem using a custom JsonConverter
class like this:
class ParentCollectionConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(ParentCollection);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
ParentCollection pc = new ParentCollection();
JArray array = JArray.Load(reader);
foreach (var item in array)
{
pc.Add(item.ToObject<ChildDTO>());
}
return pc;
}
public override bool CanWrite
{
get { return false; }
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
To use the converter, pass it to DeserializeObject<T>
like this:
ParentCollection pCollection =
JsonConvert.DeserializeObject<ParentCollection>(json, new ParentCollectionConverter());
Working demo here: https://dotnetfiddle.net/3GM22c
Upvotes: 3
Reputation: 817
Good morning. If you need the ChildDto's list, please convert it to List. Please refer to the code and image below. Many thanks.
string file = System.IO.File.ReadAllText("Children_CA.txt");
var results1 = JsonConvert.DeserializeObject<List<ChildDTO>>(file);
Upvotes: 0