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!"}
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!"}
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)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With