C
C#14mo ago
PhantomRow

❔ Deserialize Object that can have both Array and Object structure

I provided example fiddle, please help me to figure this out. link attribute can have both [{},{},{}] structure or {} structure. I'm trying from json string deserialize to object. https://dotnetfiddle.net/ikXhPf https://dotnetfiddle.net/sDwJeO (same) Thank you! 🙂
6 Replies
PhantomRow
PhantomRowOP14mo ago
if (reader.TokenType == JsonToken.StartArray) { return serializer.Deserialize<LinkArray>(reader); } else if (reader.TokenType == JsonToken.StartObject) { return serializer.Deserialize<LinkElement>(reader); } else { throw new JsonSerializationException("Unexpected token type when deserializing 'link'."); } this doesn't work either
PhantomRow
PhantomRowOP14mo ago
I have Entry class, I want to deserialize Entry class, Entry class has attribute link that can be both type Link and List<Link>, I provided in the fiddle best I could do. Only workaround that I can think of is using try catch where I create class Entry1 that has Link link attribute and Entry2 that has List<Link> link attribute. Any other suggestion. I've read your link it somehow didn't help me.
friedice
friedice14mo ago
var token = JToken.Load(reader);

if (token.Type == JTokenType.Array)
{
return new LinkArray { Elements = token.ToObject<List<Link>>(serializer) };
}
var token = JToken.Load(reader);

if (token.Type == JTokenType.Array)
{
return new LinkArray { Elements = token.ToObject<List<Link>>(serializer) };
}
try this
PhantomRow
PhantomRowOP14mo ago
that should help, I solved it in similar way, but you are lifesaver because if I didn't this would be everything, so you are MVP , thank you ❤️ When I do return Json(result), I get link:{} -and I should get { atr1:value1} or [{atr1:val1,atr2:val2}], Values are there in result, and I can serializeObject to string and have attributes there Any idea why am I missing link properties values? -how to get them? JToken token = JToken.Load(reader); if (token.Type == JTokenType.Array) { // If it's an array, deserialize as a LinkArray. var linkArray = new LinkArray { Elements = token.ToObject<List<Link>>() }; return linkArray; } else if (token.Type == JTokenType.Object) { // If it's an object, deserialize as a LinkElement. return token.ToObject<LinkElement>(); } this was solution the reason seems to be json function uses text json, and I implemented read write in newtonsoft , i managed to write converters using system.text.json, so now it works , my previous converter was newtonsoft, somehow json method uses text.json I didn't manage to not have attribute name values escaped in string "attributeName", tried with naming policy
Accord
Accord14mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server