kartheeki j
kartheeki j

Reputation: 2306

How to remove NULL in json using c#?

i am getting Null value in json. I am using JavaScriptSerializer for converting to json. Please any one help me how to solve my issue. Thanks in advance.

Json:

"Boardingpoints": [{
  "location": "Shapur,",
  "id": 2776,
  "time": "08:45PM"
 }, {
  "location": "Ameerpet,Jeans Corner",
  "id": 6,
  "time": "09:00PM"
 }, {
  "location": "Vivekananda Nagar Colony,",
  "id": 2347,
  "time": "08:45PM"
 }, {
  "location": "Nampally,",
  "id": 2321,
  "time": "09:30PM"
 }, {
  "location": "Kondapur,Toyota Show room",
  "id": 2244,
  "time": "09:10PM"
 }, {
  "location": "KUKATPALLY,JNTU",
  "id": 2230,
  "time": "08:30PM"
 }, null, null, {
  "location": "L.B Nagar,Near Petrol Bunk",
  "id": 2247,
  "time": "09:00PM"
 }, null, null, {
  "location": "Moosapet,",
  "id": 2781,
  "time": "10:30PM"
 }, null, null, null, null, null, null, {
  "location": "S.R.Nagar bus stop,S.R.Nagar bus stop",
  "id": 4090,
  "time": "10:00PM"
 }],

class:

 public class Bordingpoints
        {
            public string location { get; set; }
            public int id { get; set; }
            public string time { get; set; }

        }

Deserialization:

 var bp = new Bordingpoints[array1.Count];
                    for (int i = 0; i < array1.Count; i++)
                    {
                        try
                        {
                            JArray pickups = (JArray)array1[i]["boardingPoints"];
                            for (int j = 0; j < pickups.Count; j++)
                            {
                                string location = (string)pickups[j]["location"];
                                int id = (int)pickups[j]["id"];
                                string time = (string)pickups[j]["time"];

                                if (!bpid.Contains(id))
                                {
                                    bp[i] = new Bordingpoints();
                                    bp[i].location = location;
                                    bp[i].id = id;
                                    bp[i].time = time;
                                    bpid.Add(id);

                                }
                            }
                        }


JavaScriptSerializer js = new JavaScriptSerializer();

                    string bdpt = js.Serialize(bp);

Based on some condition i skipped some of the objects, for that time i am getting null value. please help me.

Upvotes: 1

Views: 200

Answers (1)

Captain0
Captain0

Reputation: 2623

there is null items in your array. You could try the following. There are probably better ways, but this should do the trick

Replace

string bdpt = js.Serialize(bp);

with

string bdpt = js.Serialize(bp.Where(p=>p!=null));

Upvotes: 3

Related Questions