gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 23:05:38 24 4
gpt4 key购买 nike

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

类(class):

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

基于某些情况,我跳过了一些对象,那时我得到的是空值。请帮助我。

最佳答案

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

替换

string bdpt = js.Serialize(bp);

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

关于c# - 如何使用 C# 删除 json 中的 NULL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41296879/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com