如何从JSON删除不需要的字符串属性 [英] How to remove unwanted string properties from JSON

查看:113
本文介绍了如何从JSON删除不需要的字符串属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我的输入遵循JSON:

Suppose my input is following JSON:

{obj: { x: "", y: "test str" }, myStr: "Hi"}

我想删除所有空字符串和值为 N/A 的字符串,以使输出变为:

I would like to remove all empty strings and strings with a value of N/A so that the output becomes:

{obj: { y: "test str" }, myStr: "Hi"}

请注意,以上输入只是示例输入文件.

Note the above input is just a sample input file.

我试图写一些代码:

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

但是我无法获得所需的输出.

But I'm not able to get the desired output.

推荐答案

要使用 DefaultValueHandling 忽略默认的空字符串,您需要将 DefaultValue 添加到x属性

to ignore default empty string using DefaultValueHandling you need to add DefaultValue to x property

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

更新:

这里是有效的 dotnetfiddle

using System;
using Newtonsoft.Json;
using System.ComponentModel;
                    
public class Program
{
        
    public static void Main()
    {
        //var myClass = new MyClasss();
        //var myObj = new Obj();
        
        //myObj.x="";
        //myObj.y="test str";
        
        //myClass.myStr = "Hi";
        //myClass.obj= myObj;
        
        string json = @"{obj: { x: '', y: 'test str' }, myStr: 'Hi'}";
        MyClasss myClass = JsonConvert.DeserializeObject<MyClasss>(json);

        var settings = new JsonSerializerSettings();
        
        settings.NullValueHandling = NullValueHandling.Ignore;
        settings.DefaultValueHandling = DefaultValueHandling.Ignore;
        
        
        Console.WriteLine(JsonConvert.SerializeObject(myClass, settings));
    }
}

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

    }

    public class MyClasss    {
        public Obj obj { get; set; } 
        [DefaultValue("")]
        public string myStr { get; set; } 

    }

这篇关于如何从JSON删除不需要的字符串属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆