如何使用c#删除json中的NULL?

时间:2016-12-23 07:16:19

标签: c# asp.net json null

我在json中获得Null值。我正在使用JavaScriptSerializer转换为json。请任何人帮我解决我的问题。提前谢谢。

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"
 }],

类:

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

        }

反序列化:

 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);

基于某些条件我跳过了一些对象,那时候我得到了空值。请帮帮我。

1 个答案:

答案 0 :(得分:3)

数组中有空项。您可以尝试以下方法。可能有更好的方法,但这应该是技巧

替换

string bdpt = js.Serialize(bp);

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