我有以下JSON,其中某些属性具有空字符串,即“”或空值
{
"allOrNone":false,
"records":[
{
"Address__c":"Street",
"ConsentToComm__c":"",
"EmailCLDate__c":"",
"attributes":{
"type":"Stage_FF_Hot_Alerts__c"
}
}
]
}
我必须从此JSON中删除空字符串和空值属性。我如何删除它们。我在C#中执行此操作。删除空字符串后所需的JSON和null将为:
{
"allOrNone":false,
"records":[
{
"Address__c":"Street",
"attributes":{
"type":"Stage_FF_Hot_Alerts__c"
}
}
]
}
答案 0 :(得分:2)
我已经解决了这个问题。我已在序列化过程中删除了空值。
string JSONstring = JsonConvert.SerializeObject(dt, new
JsonSerializerSettings()
{
NullValueHandling = NullValueHandling.Ignore,
});
然后通过以下代码删除空字符串值
var temp = JArray.Parse(JSONstring);
temp.Descendants()
.OfType<JProperty>()
.Where(attr => attr.Value.ToString() == "")
.ToList() // you should call ToList because you're about to changing the result, which is not possible if it is IEnumerable
.ForEach(attr => attr.Remove()); // removing unwanted attributes
JSONstring = temp.ToString();
答案 1 :(得分:0)
这可能有帮助
namespace JSON
{
using System;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
public partial class Root
{
[DefaultValue("")]
[JsonProperty("allOrNone")]
public bool AllOrNone { get; set; }
[DefaultValue("")]
[JsonProperty("records")]
public Record[] Records { get; set; }
}
public partial class Record
{
[DefaultValue("")]
[JsonProperty("Address__c")]
public string AddressC { get; set; }
[DefaultValue("")]
[JsonProperty("ConsentToComm__c")]
public string ConsentToCommC { get; set; }
[DefaultValue("")]
[JsonProperty("EmailCLDate__c")]
public string EmailClDateC { get; set; }
[DefaultValue("")]
[JsonProperty("attributes")]
public Attributes Attributes { get; set; }
}
public partial class Attributes
{
[DefaultValue("")]
[JsonProperty("type")]
public string Type { get; set; }
}
public partial class Root
{
public static Root FromJson(string json) => JsonConvert.DeserializeObject<Root>(json, QuickType.Converter.Settings);
}
public static class Serialize
{
public static string ToJson(this Root self) => JsonConvert.SerializeObject(self, QuickType.Converter.Settings);
}
internal static class Converter
{
public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
ContractResolver = ShouldSerializeContractResolver.Instance,
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
DateParseHandling = DateParseHandling.None,
Converters = {
new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
},
};
}
}