Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove empty string json values in complex json object?

I'm trying to upload JSON values to AWS Dynamo, and it looks like it's giving me a 400-type error when I upload values that have any properties with "" as values. The app I'm writing is a C# app.

What's the best way to remove any keys that have value of ""? I've seen how to remove null values, but I'm not sure this applies.

Say:

{myObj: { x: "", y: "test str" }, myStr: "hello world!"}

Becomes:

{myObj: { y: "test str" }, myStr: "hello world!"}
like image 478
Abarnett Avatar asked Mar 10 '23 17:03

Abarnett


2 Answers

If you are using Newtonsoft's Json.NET library, you can play with JsonSerializerSettings and DefaultValue attribute:

public class Rootobject
{
    public Myobj myObj { get; set; }
    public string myStr { get; set; }
}

public class Myobj
{
    [DefaultValue("")]
    public string x { get; set; }
    [DefaultValue("")]
    public string y { get; set; }
}

var originalSerializedObject = "{myObj: { x: \"\", y: \"test str\" }, myStr: \"hello world!\"}";

var deserializedObject = JsonConvert.DeserializeObject<Rootobject>(originalSerializedObject);

var serializerSettings = new JsonSerializerSettings 
                             { 
                                NullValueHandling = NullValueHandling.Ignore, 
                                DefaultValueHandling = DefaultValueHandling.Ignore 
                             };

var newSerializedObject = JsonConvert.SerializeObject(deserializedObject, serializerSettings);

Console.WriteLine(newSerializedObject);
//{"myObj":{"y":"test str"},"myStr":"hello world!"}
like image 118
Anderson Pimentel Avatar answered Mar 24 '23 04:03

Anderson Pimentel


If you do not want it to be applied to every single field, you could just add the following on the field that you would want to ignore when empty.

[DefaultValue("")]
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, 
DefaultValueHandling = DefaultValueHandling.Ignore)]
like image 39
Kash Avatar answered Mar 24 '23 04:03

Kash