-1

I have the following JSON in which some attributes have empty string i.e. "" or null values

{  
   "allOrNone":false,
   "records":[  
  {  
     "Address__c":"Street",
     "ConsentToComm__c":"",
     "EmailCLDate__c":"",
     "attributes":{  
        "type":"Stage_FF_Hot_Alerts__c"
     }
  }
 ]
}

I have to remove the empty string and null value attributes from this JSON. How can i remove them. I am doing this in C#. Required JSON after removing empty strings and null would be:

{  
   "allOrNone":false,
   "records":[  
  {  
     "Address__c":"Street",
     "attributes":{  
        "type":"Stage_FF_Hot_Alerts__c"
     }
  }
 ]
}
Waleed Naveed
  • 2,293
  • 2
  • 29
  • 57
  • to be clear: in this scenario, you *just* have JSON that you want to post-process - it isn't tied to a specific object model that you're serializing? (both ways are possible, but have very different implementations) – Marc Gravell Jan 15 '19 at 11:31
  • Yes, i want to process the JSON. I read data from database and store it in the DataTable, this data table is then serialized. – Waleed Naveed Jan 15 '19 at 11:33
  • 3
    So, what's stopping you? – Zohar Peled Jan 15 '19 at 11:33
  • how can i remove the attributes with empty string values i.e. "". I dont want those attributes in my JSON. For more clarification you can see the input JSON and the JSON which i am expecting as output. – Waleed Naveed Jan 15 '19 at 11:36
  • @Izzy since this isn't a serialization scenario, I don't think that applies – Marc Gravell Jan 15 '19 at 11:38
  • It only removes null values not empty string values @Izzy – Waleed Naveed Jan 15 '19 at 11:39
  • Which way do you want? decode-search-remove-encode or a regex replace? – shingo Jan 15 '19 at 12:40
  • There are already some related or duplicate questions including [Prevent serialization if value is null or whitespace in JSON.NET](https://stackoverflow.com/q/50840347/3744182), [Remove empty string properties from json serialized object](https://stackoverflow.com/q/41287224/3744182). – dbc Jan 15 '19 at 19:45
  • In both of these links, they have made custom/separate classes, but my requirement was that i could not create any separate class. I have already mentioned it in a comment on an answer @dbc – Waleed Naveed Jan 16 '19 at 07:24
  • @WaleedNaveed - no, the answer to [*Prevent serialization if value is null or whitespace in JSON.NET*](https://stackoverflow.com/a/50841197/3744182) and [this answer to *Remove empty string properties from json serialized object*](https://stackoverflow.com/a/53878125/3744182) both use a [custom contract resolver](https://www.newtonsoft.com/json/help/html/contractresolver.htm#CustomIContractResolverExamples) and so do not require any modifications to your data model. – dbc Jan 16 '19 at 07:32

2 Answers2

6

I have resolved this problem. I have removed the null values during serialization.

string JSONstring = JsonConvert.SerializeObject(dt, new 
JsonSerializerSettings()
{
            NullValueHandling = NullValueHandling.Ignore,
});

And after that empty string values are removed through the following code

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();
Waleed Naveed
  • 2,293
  • 2
  • 29
  • 57
0

This may Help

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 }
            },
        };
    }
}
luis
  • 1
  • 2