如何使用Json.NET以与对象相同的方式序列化JObject? [英] How to serialize a JObject the same way as an object with Json.NET?

查看:75
本文介绍了如何使用Json.NET以与对象相同的方式序列化JObject?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何控制将JObject序列化为字符串?

How do I control the serialization of a JObject to string?

我有一些返回JObject的API,通常我会应用一些更改并保持或返回它们.我想避免持久保留null属性并应用一些其他格式,但是JsonConvert似乎完全忽略了我的设置.

I have some APIs that return a JObject and I usually apply some changes and persist or return them. I want to avoid persisting null properties and apply some additional formatting, but JsonConvert seems to completely ignore my settings.

这是问题的示例:

// startup.cs has the following
services.AddMvc().AddJsonOptions(o =>
{
    o.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
});

public class SampleController : Controller
{
    JsonSerializerSettings _settings = new JsonSerializerSettings
    {
        NullValueHandling = NullValueHandling.Ignore
    };

    [HttpPost]
    [Route("object")]
    public object PostObject([FromBody] SomeObject data)
    {
        return JsonConvert.SerializeObject(data, _settings);
    }

    [HttpPost]
    [Route("jobject")]
    public object PostJObject([FromBody] JObject data)
    {
        return JsonConvert.SerializeObject(data, _settings);
    }

    public class SomeObject
    {
        public string Foo { get; set; }
        public string Bar { get; set; }
    }
}

发布{ "Foo": "Foo", "Bar": null }:

  • /object返回{"Foo":"Foo"}
  • /jobject返回{"Foo":"Foo","Bar":null}
  • /object returns {"Foo":"Foo"}
  • /jobject returns {"Foo":"Foo","Bar":null}

我希望JObject方法返回与使用对象相同的输出json.我如何在不创建帮助者的情况下实现这一目标?有没有办法使用相同的设置来序列化JObject?

I want the JObject method to return the same output json as if I were using an object. How do I achieve this without creating helpers? Is there a way to serialize the JObject using the same settings?

推荐答案

序列化JObject时,将写入其原始JSON. JsonSerializerSettings不影响其书面JSON.

When a JObject is serialized its raw JSON is written. JsonSerializerSettings do not effect its written JSON.

这篇关于如何使用Json.NET以与对象相同的方式序列化JObject?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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