Elas Elas - 1 month ago 12
JSON Question

Double included object while serializing collection class

I'm trying to serialize class Poll, which looks like that:

class Poll
{
(...) //methods
public AnswersCollection answers { get; set; }
public TagsCollection tags { get; set; }
public string question { get; set; }
}


As you can see, I have "TagsCollection" and "AnswersCollection", which both look pretty similiar, so I'll show only one of them.

class AnswersCollection
{
(...) //methods
public List<Answer> answers { get; set; }
}


And, finnaly, Answer class.

class Answer
{
(...) //methods
public string name { get; set; }
public uint voteQuantity { get; set; }
}


All clases have default public constructor (without parameters) so JSON.NET doesn't have any problems with serialization.

Problem is with AnswersCollection (which is encapsulation), because of it, JSON output looks like that:

{
"answers":{
"answers":[
{
"name":"Foo",
"voteQuantity":45
},
{
"name":"Bar",
"voteQuantity":30
}
]
},
"tags":{
"tags":[
{
"name":"FooTag",
"id":5
},
{
"name":"BarTag",
"id":4
}
]
},
"question":"Question?"
}


As you can see, the problem is with structures like "answers":{ "answers": [(...)] }

Is there option to serialize it to structures like "answers" :[(...)] without second "answers" tag?
I tried to use properties like "isReference" but it didn't worked.

Answer

The serialization is actually doing exactly what is expected of it.

I know it will not exactly answer your original question as to whether there is a way to ask Json.Net to do what you want, but your best option here would be to have inheritence instead of composition for your AnswersCollection.

Since the name suggests the class is a collection of answers, why not make it inherit from List<Answer> instead of having a property of this type ?

If you really can't change the structure of your object, you could go the long-hard way, and implement your own JsonConverter to have an absolute control of how your properties are going to be serialized / deserialized.

You would have to apply the JsonConverterAttribute to the Poll.answers property to tell Json.Net to use your custom serializer.

However, I would highly recommend not taking that approach, if you can avoid it.

Off-topic as a side note: you should consider using a CamelCasePropertyNamesContractResolver to tell your serializer to use CamelCasing when serializing your properties, so you don't have to use camelCasing on your property itself: answers should be spelled Answers if you want to follow common naming practices.

Comments