2

I have a class like this:

public class media
{
    public string id { get; set; }
    public string code { get; set; }
    public string url { get; set; }
    public string comment_count { get; set; }
    public string like_count { get; set; }

    public int no { get; set; }
}

I create a list

List<media> my_stack = new List<media>();

I added some media in my list;

media new_media = new media();

new_media.id = "some id";
new_media.code = "value";
new_media.url = "value";

my_stack.Add(new_media);

new_media = new media();

new_media.id = "some id";
new_media.url = "value";

my_stack.Add(new_media);

new_media = new media();

new_media.id = "some id";
new_media.url = "value";
new_media.code = "value";
new_media.comment_count = "value";
new_media.like_count = "value";

my_stack.Add(new_media);

When I SerializeObject List<media> media result is full of null properties.

[
{"id":"some id", "code":"value", "url":"value","comment_count":null, "like_count": null, "no":0},
{"id":"some id", "code":null, "url":"value","comment_count":null, "like_count": null, "no":0},
{"id":"some id", "code":"value", "url":"value","comment_count":"value", "like_count": "value", "no":0}
]

I don't want to null values. I tried two things about NullValueHandling but not working for me.

1 : How to ignore a property in class if null, using json.net

2 : http://www.tecsupra.com/serializing-only-some-properties-of-an-object-to-json-using-newtonsoft-json-net/

I think NullValueHandling not working on List<object> Serializing?

How i can remove null values in my List json?

Community
  • 1
  • 1
Soner B
  • 311
  • 3
  • 13

1 Answers1

1

As i understood your problem, you dont need the properties in the json object array that you havnt set value for - which will be set as null as you are getting now. In that case, how about creating an anonymous object and then serializing it to json? Create an array of anonymous object, have only the properties you need in each object, then do a json convert. Use JObject for this.

http://www.newtonsoft.com/json/help/html/CreateJsonAnonymousObject.htm

Developer
  • 6,240
  • 3
  • 18
  • 24