简体   繁体   English

如何在复杂的json对象中删除空字符串json值?

[英]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. 我正在尝试将JSON值上传到AWS Dynamo,当我上传具有任何属性值为“”的值时,它看起来像是给我一个400型错误。 The app I'm writing is a C# app. 我正在编写的应用程序是一个C#应用程序。

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: 如果您使用的是Newtonsoft的Json.NET库,则可以使用JsonSerializerSettingsDefaultValue属性:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM