【问题标题】:How to remove NULL in json using c#?如何使用 c# 删除 json 中的 NULL?
【发布时间】:2016-12-23 07:16:18
【问题描述】:

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

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

【问题讨论】:

标签: c# asp.net json null


【解决方案1】:

您的数组中有空项目。您可以尝试以下方法。可能有更好的方法,但这应该可以解决问题

替换

string bdpt = js.Serialize(bp);

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-25
    • 1970-01-01
    • 2015-04-11
    • 1970-01-01
    • 1970-01-01
    • 2015-10-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多