I am new into json.net, so any help would be appreciated.
I am using the net 2.0 version of json.net, because i need to integrate it in Unity3d engine Suggested answer (using nullvaluehandling) just don't work! Should i consider this as restiction of the oldest version?
So, a have an object like this:
Object ()
{
ChildObject ChildObject1;
ChildObject ChildObject2;
}
ChildObject ()
{
Property1;
Property2;
}
I want json.net to serialize only not null properties of all objects, including child objects. So if i instatiate only property1 of ChildObject1 and property2 of ChildObject2, the string from JsonConvert will be like this:
{
"ChildObject1":
{
"Property1": "10"
},
"ChildObject1":
{
"Property2":"20"
}
}
But default behaviour creates string like this:
{
"ChildObject1":
{
"Property1": "10",
"Property2": "null"
},
"ChildObject2":
{
"Property1": "null,
"Property2":"20"
}
}
I know about NullValueHandling, but it is not working corretly in my case! It ignore only null properties of the parent object (object that we are serializing), but if this parent object has some childs, it will not ignore null properties of this child objects. My situation is different.
If even one property of a child object is not null, it serialize it to a string with one not-null property and others null.
UPD example of my code:
i have nested classes
My object is like this:
public class SendedMessage
{
public List<Answer> Answers { get; set; }
public AnswerItem Etalon {get; set;}
}
public class Answer ()
{
public AnswerItem Item { get; set; }
}
public class AnswerItem ()
{
public string ID { get; set; }
public bool Result { get; set; }
public int Number { get; set; }
}
i instatiate a SendedMessage object like this:
new SendedMessage x;
x.Etalon = new AnswerItem();
x.Etalon.Result = true;
than i use
string ignored = JsonConvert.SerializeObject(x,
Formatting.Indented,
new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
and it make this string:
{ "Etalon": {"ID" = "null", "Result" = "false", Number" = "null"}}
so it really ignore the null object Answers (a List), but do not ignore the null properties of a child objects.
Thanks for help!