gpt4 book ai didi

c# - Json.net 忽略子对象的空值

转载 作者:行者123 更新时间:2023-11-30 21:46:02 26 4
gpt4 key购买 nike

我是 json.net 的新手,所以任何帮助将不胜感激。

我正在使用 net 2.0 版本的 json.net,因为我需要将它集成到 Unity3d 引擎中 建议的答案(使用 nullvaluehandling)根本不起作用!我应该将其视为对最旧版本的限制吗?

所以,有一个像这样的对象:

Object ()
{
ChildObject ChildObject1;
ChildObject ChildObject2;
}

ChildObject ()
{
Property1;
Property2;
}

我希望 json.net 仅序列化所有对象(包括子对象)的非空属性。因此,如果我仅实例化 ChildObject1 的 property1 和 ChildObject2 的 property2,则来自 JsonConvert 的字符串将如下所示:

{
"ChildObject1":
{
"Property1": "10"
},
"ChildObject1":
{
"Property2":"20"
}
}

但默认行为会创建这样的字符串:

{
"ChildObject1":
{
"Property1": "10",
"Property2": "null"
},
"ChildObject2":
{
"Property1": "null,
"Property2":"20"
}
}

我知道 NullValueHandling,但它在我的情况下无法正常工作!它只忽略父对象(我们正在序列化的对象)的空属性,但是如果这个父对象有一些子对象,它不会忽略这个子对象的空属性。我的情况不同。

即使子对象的一个​​属性不为空,它也会将其序列化为一个字符串,其中一个属性为非空属性,其他属性为空。


我的代码的 UPD 示例:

我有嵌套类

我的对象是这样的:

public class SendedMessage
{
public List<Answer> Answers { get; set; }
public AnswerItem Etalon {get; set;}
}

public class Answer ()
{
public AnswerItem Item { get; set; }
}

public class AnswerItem ()
{
public string ID { get; set; }
public bool Result { get; set; }
public int Number { get; set; }
}

我像这样实例化一个 SendedMessage 对象:

new SendedMessage x;
x.Etalon = new AnswerItem();
x.Etalon.Result = true;

比我用的

string ignored = JsonConvert.SerializeObject(x,
Formatting.Indented,
new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });

它使这个字符串:

{ “Etalon”:{“ID” = “null”,“Result” = “false”,Number” = “null”}}

所以它真的忽略了空对象Answers(一个List),但是没有忽略一个子对象的空属性。

感谢您的帮助!

最佳答案

使用这个:

string ignored = sonConvert.SerializeObject(movie,
Formatting.Indented,
new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });

例子如下:

public class Movie
{
public string Name { get; set; }
public string Description { get; set; }
public string Classification { get; set; }
public string Studio { get; set; }
public DateTime? ReleaseDate { get; set; }
public List<string> ReleaseCountries { get; set; }
}

static void Main(string[] args)
{
Movie movie = new Movie();
movie.Name = "Bad Boys III";
movie.Description = "It's no Bad Boys";

string included = JsonConvert.SerializeObject(movie,
Formatting.Indented,new JsonSerializerSettings { });

// {
// "Name": "Bad Boys III",
// "Description": "It's no Bad Boys",
// "Classification": null,
// "Studio": null,
// "ReleaseDate": null,
// "ReleaseCountries": null
// }

string ignored = JsonConvert.SerializeObject(movie,
Formatting.Indented,
new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });

// {
// "Name": "Bad Boys III",
// "Description": "It's no Bad Boys"
// }
}

关于c# - Json.net 忽略子对象的空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39571487/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com