How to serialize a JObject the same way as an object with Json.NET?
How do I control the serialization of a JObject to string?
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.
Here is the sample of the problem:
// 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; }
}
}
Posting { "Foo": "Foo", "Bar": null }
:
/object
returns{"Foo":"Foo"}
/jobject
returns{"Foo":"Foo","Bar":null}
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?
c# json.net
add a comment |
How do I control the serialization of a JObject to string?
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.
Here is the sample of the problem:
// 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; }
}
}
Posting { "Foo": "Foo", "Bar": null }
:
/object
returns{"Foo":"Foo"}
/jobject
returns{"Foo":"Foo","Bar":null}
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?
c# json.net
Doesn'tJObject
have aToString
method that returns JSON?
– Heretic Monkey
Oct 25 '16 at 16:30
I don't think you can "edit" aJObject
during serialization withJsonConvert.SerializObject()
. AJObject
has already been serialized so allJsonConvert
is doing is emit it more-or-less verbatim. See Newtonsoft Json.Net serialize JObject doesn't ignore nulls, even with the right settings. For a workaround see JSON.NET serialize JObject while ignoring null properties,
– dbc
Oct 25 '16 at 17:12
@MikeMcCaughan JObject.ToString converts the object to json, but doesn't have any overload to accept the settings object.
– Natan
Oct 25 '16 at 18:32
add a comment |
How do I control the serialization of a JObject to string?
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.
Here is the sample of the problem:
// 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; }
}
}
Posting { "Foo": "Foo", "Bar": null }
:
/object
returns{"Foo":"Foo"}
/jobject
returns{"Foo":"Foo","Bar":null}
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?
c# json.net
How do I control the serialization of a JObject to string?
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.
Here is the sample of the problem:
// 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; }
}
}
Posting { "Foo": "Foo", "Bar": null }
:
/object
returns{"Foo":"Foo"}
/jobject
returns{"Foo":"Foo","Bar":null}
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?
c# json.net
c# json.net
edited Oct 25 '16 at 16:15
asked Oct 25 '16 at 15:49
Natan
2,66121837
2,66121837
Doesn'tJObject
have aToString
method that returns JSON?
– Heretic Monkey
Oct 25 '16 at 16:30
I don't think you can "edit" aJObject
during serialization withJsonConvert.SerializObject()
. AJObject
has already been serialized so allJsonConvert
is doing is emit it more-or-less verbatim. See Newtonsoft Json.Net serialize JObject doesn't ignore nulls, even with the right settings. For a workaround see JSON.NET serialize JObject while ignoring null properties,
– dbc
Oct 25 '16 at 17:12
@MikeMcCaughan JObject.ToString converts the object to json, but doesn't have any overload to accept the settings object.
– Natan
Oct 25 '16 at 18:32
add a comment |
Doesn'tJObject
have aToString
method that returns JSON?
– Heretic Monkey
Oct 25 '16 at 16:30
I don't think you can "edit" aJObject
during serialization withJsonConvert.SerializObject()
. AJObject
has already been serialized so allJsonConvert
is doing is emit it more-or-less verbatim. See Newtonsoft Json.Net serialize JObject doesn't ignore nulls, even with the right settings. For a workaround see JSON.NET serialize JObject while ignoring null properties,
– dbc
Oct 25 '16 at 17:12
@MikeMcCaughan JObject.ToString converts the object to json, but doesn't have any overload to accept the settings object.
– Natan
Oct 25 '16 at 18:32
Doesn't
JObject
have a ToString
method that returns JSON?– Heretic Monkey
Oct 25 '16 at 16:30
Doesn't
JObject
have a ToString
method that returns JSON?– Heretic Monkey
Oct 25 '16 at 16:30
I don't think you can "edit" a
JObject
during serialization with JsonConvert.SerializObject()
. A JObject
has already been serialized so all JsonConvert
is doing is emit it more-or-less verbatim. See Newtonsoft Json.Net serialize JObject doesn't ignore nulls, even with the right settings. For a workaround see JSON.NET serialize JObject while ignoring null properties,– dbc
Oct 25 '16 at 17:12
I don't think you can "edit" a
JObject
during serialization with JsonConvert.SerializObject()
. A JObject
has already been serialized so all JsonConvert
is doing is emit it more-or-less verbatim. See Newtonsoft Json.Net serialize JObject doesn't ignore nulls, even with the right settings. For a workaround see JSON.NET serialize JObject while ignoring null properties,– dbc
Oct 25 '16 at 17:12
@MikeMcCaughan JObject.ToString converts the object to json, but doesn't have any overload to accept the settings object.
– Natan
Oct 25 '16 at 18:32
@MikeMcCaughan JObject.ToString converts the object to json, but doesn't have any overload to accept the settings object.
– Natan
Oct 25 '16 at 18:32
add a comment |
3 Answers
3
active
oldest
votes
When a JObject
is serialized its raw JSON is written. JsonSerializerSettings
do not effect its written JSON.
6
-1; this answer doesn't mean anything to me. What's the "raw JSON" of aJObject
? The term isn't used in theJObject
docs, and doesn't have an obvious meaning, especially given that aJObject
can containJToken
s like dates and GUIDs that aren't part of the JSON spec and have multiple possible serialisations.
– Mark Amery
Jun 19 '17 at 14:46
add a comment |
The only way I was able to do this is by first converting the JObject
to a string
, then deserializing that string into an ExpandoObject
(don't deserialize to object
because you'll get back a JObject
). The ExpandoObject
is like a dictionary, which will cause JsonConvert
to actually invoke the configured name case strategy. I'm not sure why the author of Newtonsoft.Json didn't handle JObject types the same way as they seem to be doing for dictionary types, but at least this work around works.
Example:
// Construct a JObject.
var jObject = JObject.Parse("{ SomeName: "Some value" }");
// Deserialize the object into an ExpandoObject (don't use object, because you will get a JObject).
var payload = JsonConvert.DeserializeObject<ExpandoObject>(jObject.ToString());
// Now you can serialize the object using any serializer settings you like.
var json = JsonConvert.SerializeObject(payload, new JsonSerializerSettings
{
ContractResolver = new DefaultContractResolver
{
NamingStrategy = new CamelCaseNamingStrategy
{
// Important! Make sure to set this to true, since an ExpandoObject is like a dictionary.
ProcessDictionaryKeys = true,
}
}
}
);
Console.WriteLine(json); // Outputs: {"someName":"Some value"}
I picked-up the trick with the ExpandoObject
here: JObject & CamelCase conversion with JSON.Net
add a comment |
A solution that well integrates with NewtonSoft framework is to provide a custom JObject converter that honours the NamingStrategy
.
JObject Custom Converter
public class JObjectNamingStrategyConverter : JsonConverter<JObject> {
private NamingStrategy NamingStrategy { get; }
public JObjectNamingStrategyConverter (NamingStrategy strategy) {
if (strategy == null) {
throw new ArgumentNullException (nameof (strategy));
}
NamingStrategy = strategy;
}
public override void WriteJson (JsonWriter writer, JObject value, JsonSerializer serializer) {
writer.WriteStartObject ();
foreach (JProperty property in value.Properties ()) {
var name = NamingStrategy.GetPropertyName (property.Name, false);
writer.WritePropertyName (name);
serializer.Serialize (writer, property.Value);
}
writer.WriteEndObject ();
}
public override JObject ReadJson (JsonReader reader, Type objectType, JObject existingValue, bool hasExistingValue, JsonSerializer serializer) {
throw new NotImplementedException ();
}
}
Usage
var snakeNameStrategy = new SnakeCaseNamingStrategy ();
var jsonSnakeSettings = new JsonSerializerSettings {
Formatting = Formatting.Indented,
Converters = new { new JObjectNamingStrategyConverter (snakeNameStrategy) },
ContractResolver = new DefaultContractResolver {
NamingStrategy = snakeNameStrategy
},
};
var json = JsonConvert.SerializeObject (obj, jsonSnakeSettings);
You can find a working PoC on GitHub.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f40244395%2fhow-to-serialize-a-jobject-the-same-way-as-an-object-with-json-net%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
When a JObject
is serialized its raw JSON is written. JsonSerializerSettings
do not effect its written JSON.
6
-1; this answer doesn't mean anything to me. What's the "raw JSON" of aJObject
? The term isn't used in theJObject
docs, and doesn't have an obvious meaning, especially given that aJObject
can containJToken
s like dates and GUIDs that aren't part of the JSON spec and have multiple possible serialisations.
– Mark Amery
Jun 19 '17 at 14:46
add a comment |
When a JObject
is serialized its raw JSON is written. JsonSerializerSettings
do not effect its written JSON.
6
-1; this answer doesn't mean anything to me. What's the "raw JSON" of aJObject
? The term isn't used in theJObject
docs, and doesn't have an obvious meaning, especially given that aJObject
can containJToken
s like dates and GUIDs that aren't part of the JSON spec and have multiple possible serialisations.
– Mark Amery
Jun 19 '17 at 14:46
add a comment |
When a JObject
is serialized its raw JSON is written. JsonSerializerSettings
do not effect its written JSON.
When a JObject
is serialized its raw JSON is written. JsonSerializerSettings
do not effect its written JSON.
answered Oct 27 '16 at 1:17
James Newton-King
30.4k1994115
30.4k1994115
6
-1; this answer doesn't mean anything to me. What's the "raw JSON" of aJObject
? The term isn't used in theJObject
docs, and doesn't have an obvious meaning, especially given that aJObject
can containJToken
s like dates and GUIDs that aren't part of the JSON spec and have multiple possible serialisations.
– Mark Amery
Jun 19 '17 at 14:46
add a comment |
6
-1; this answer doesn't mean anything to me. What's the "raw JSON" of aJObject
? The term isn't used in theJObject
docs, and doesn't have an obvious meaning, especially given that aJObject
can containJToken
s like dates and GUIDs that aren't part of the JSON spec and have multiple possible serialisations.
– Mark Amery
Jun 19 '17 at 14:46
6
6
-1; this answer doesn't mean anything to me. What's the "raw JSON" of a
JObject
? The term isn't used in the JObject
docs, and doesn't have an obvious meaning, especially given that a JObject
can contain JToken
s like dates and GUIDs that aren't part of the JSON spec and have multiple possible serialisations.– Mark Amery
Jun 19 '17 at 14:46
-1; this answer doesn't mean anything to me. What's the "raw JSON" of a
JObject
? The term isn't used in the JObject
docs, and doesn't have an obvious meaning, especially given that a JObject
can contain JToken
s like dates and GUIDs that aren't part of the JSON spec and have multiple possible serialisations.– Mark Amery
Jun 19 '17 at 14:46
add a comment |
The only way I was able to do this is by first converting the JObject
to a string
, then deserializing that string into an ExpandoObject
(don't deserialize to object
because you'll get back a JObject
). The ExpandoObject
is like a dictionary, which will cause JsonConvert
to actually invoke the configured name case strategy. I'm not sure why the author of Newtonsoft.Json didn't handle JObject types the same way as they seem to be doing for dictionary types, but at least this work around works.
Example:
// Construct a JObject.
var jObject = JObject.Parse("{ SomeName: "Some value" }");
// Deserialize the object into an ExpandoObject (don't use object, because you will get a JObject).
var payload = JsonConvert.DeserializeObject<ExpandoObject>(jObject.ToString());
// Now you can serialize the object using any serializer settings you like.
var json = JsonConvert.SerializeObject(payload, new JsonSerializerSettings
{
ContractResolver = new DefaultContractResolver
{
NamingStrategy = new CamelCaseNamingStrategy
{
// Important! Make sure to set this to true, since an ExpandoObject is like a dictionary.
ProcessDictionaryKeys = true,
}
}
}
);
Console.WriteLine(json); // Outputs: {"someName":"Some value"}
I picked-up the trick with the ExpandoObject
here: JObject & CamelCase conversion with JSON.Net
add a comment |
The only way I was able to do this is by first converting the JObject
to a string
, then deserializing that string into an ExpandoObject
(don't deserialize to object
because you'll get back a JObject
). The ExpandoObject
is like a dictionary, which will cause JsonConvert
to actually invoke the configured name case strategy. I'm not sure why the author of Newtonsoft.Json didn't handle JObject types the same way as they seem to be doing for dictionary types, but at least this work around works.
Example:
// Construct a JObject.
var jObject = JObject.Parse("{ SomeName: "Some value" }");
// Deserialize the object into an ExpandoObject (don't use object, because you will get a JObject).
var payload = JsonConvert.DeserializeObject<ExpandoObject>(jObject.ToString());
// Now you can serialize the object using any serializer settings you like.
var json = JsonConvert.SerializeObject(payload, new JsonSerializerSettings
{
ContractResolver = new DefaultContractResolver
{
NamingStrategy = new CamelCaseNamingStrategy
{
// Important! Make sure to set this to true, since an ExpandoObject is like a dictionary.
ProcessDictionaryKeys = true,
}
}
}
);
Console.WriteLine(json); // Outputs: {"someName":"Some value"}
I picked-up the trick with the ExpandoObject
here: JObject & CamelCase conversion with JSON.Net
add a comment |
The only way I was able to do this is by first converting the JObject
to a string
, then deserializing that string into an ExpandoObject
(don't deserialize to object
because you'll get back a JObject
). The ExpandoObject
is like a dictionary, which will cause JsonConvert
to actually invoke the configured name case strategy. I'm not sure why the author of Newtonsoft.Json didn't handle JObject types the same way as they seem to be doing for dictionary types, but at least this work around works.
Example:
// Construct a JObject.
var jObject = JObject.Parse("{ SomeName: "Some value" }");
// Deserialize the object into an ExpandoObject (don't use object, because you will get a JObject).
var payload = JsonConvert.DeserializeObject<ExpandoObject>(jObject.ToString());
// Now you can serialize the object using any serializer settings you like.
var json = JsonConvert.SerializeObject(payload, new JsonSerializerSettings
{
ContractResolver = new DefaultContractResolver
{
NamingStrategy = new CamelCaseNamingStrategy
{
// Important! Make sure to set this to true, since an ExpandoObject is like a dictionary.
ProcessDictionaryKeys = true,
}
}
}
);
Console.WriteLine(json); // Outputs: {"someName":"Some value"}
I picked-up the trick with the ExpandoObject
here: JObject & CamelCase conversion with JSON.Net
The only way I was able to do this is by first converting the JObject
to a string
, then deserializing that string into an ExpandoObject
(don't deserialize to object
because you'll get back a JObject
). The ExpandoObject
is like a dictionary, which will cause JsonConvert
to actually invoke the configured name case strategy. I'm not sure why the author of Newtonsoft.Json didn't handle JObject types the same way as they seem to be doing for dictionary types, but at least this work around works.
Example:
// Construct a JObject.
var jObject = JObject.Parse("{ SomeName: "Some value" }");
// Deserialize the object into an ExpandoObject (don't use object, because you will get a JObject).
var payload = JsonConvert.DeserializeObject<ExpandoObject>(jObject.ToString());
// Now you can serialize the object using any serializer settings you like.
var json = JsonConvert.SerializeObject(payload, new JsonSerializerSettings
{
ContractResolver = new DefaultContractResolver
{
NamingStrategy = new CamelCaseNamingStrategy
{
// Important! Make sure to set this to true, since an ExpandoObject is like a dictionary.
ProcessDictionaryKeys = true,
}
}
}
);
Console.WriteLine(json); // Outputs: {"someName":"Some value"}
I picked-up the trick with the ExpandoObject
here: JObject & CamelCase conversion with JSON.Net
edited Feb 22 at 16:20
answered Feb 22 at 15:49
Sipke Schoorstra
1,0971813
1,0971813
add a comment |
add a comment |
A solution that well integrates with NewtonSoft framework is to provide a custom JObject converter that honours the NamingStrategy
.
JObject Custom Converter
public class JObjectNamingStrategyConverter : JsonConverter<JObject> {
private NamingStrategy NamingStrategy { get; }
public JObjectNamingStrategyConverter (NamingStrategy strategy) {
if (strategy == null) {
throw new ArgumentNullException (nameof (strategy));
}
NamingStrategy = strategy;
}
public override void WriteJson (JsonWriter writer, JObject value, JsonSerializer serializer) {
writer.WriteStartObject ();
foreach (JProperty property in value.Properties ()) {
var name = NamingStrategy.GetPropertyName (property.Name, false);
writer.WritePropertyName (name);
serializer.Serialize (writer, property.Value);
}
writer.WriteEndObject ();
}
public override JObject ReadJson (JsonReader reader, Type objectType, JObject existingValue, bool hasExistingValue, JsonSerializer serializer) {
throw new NotImplementedException ();
}
}
Usage
var snakeNameStrategy = new SnakeCaseNamingStrategy ();
var jsonSnakeSettings = new JsonSerializerSettings {
Formatting = Formatting.Indented,
Converters = new { new JObjectNamingStrategyConverter (snakeNameStrategy) },
ContractResolver = new DefaultContractResolver {
NamingStrategy = snakeNameStrategy
},
};
var json = JsonConvert.SerializeObject (obj, jsonSnakeSettings);
You can find a working PoC on GitHub.
add a comment |
A solution that well integrates with NewtonSoft framework is to provide a custom JObject converter that honours the NamingStrategy
.
JObject Custom Converter
public class JObjectNamingStrategyConverter : JsonConverter<JObject> {
private NamingStrategy NamingStrategy { get; }
public JObjectNamingStrategyConverter (NamingStrategy strategy) {
if (strategy == null) {
throw new ArgumentNullException (nameof (strategy));
}
NamingStrategy = strategy;
}
public override void WriteJson (JsonWriter writer, JObject value, JsonSerializer serializer) {
writer.WriteStartObject ();
foreach (JProperty property in value.Properties ()) {
var name = NamingStrategy.GetPropertyName (property.Name, false);
writer.WritePropertyName (name);
serializer.Serialize (writer, property.Value);
}
writer.WriteEndObject ();
}
public override JObject ReadJson (JsonReader reader, Type objectType, JObject existingValue, bool hasExistingValue, JsonSerializer serializer) {
throw new NotImplementedException ();
}
}
Usage
var snakeNameStrategy = new SnakeCaseNamingStrategy ();
var jsonSnakeSettings = new JsonSerializerSettings {
Formatting = Formatting.Indented,
Converters = new { new JObjectNamingStrategyConverter (snakeNameStrategy) },
ContractResolver = new DefaultContractResolver {
NamingStrategy = snakeNameStrategy
},
};
var json = JsonConvert.SerializeObject (obj, jsonSnakeSettings);
You can find a working PoC on GitHub.
add a comment |
A solution that well integrates with NewtonSoft framework is to provide a custom JObject converter that honours the NamingStrategy
.
JObject Custom Converter
public class JObjectNamingStrategyConverter : JsonConverter<JObject> {
private NamingStrategy NamingStrategy { get; }
public JObjectNamingStrategyConverter (NamingStrategy strategy) {
if (strategy == null) {
throw new ArgumentNullException (nameof (strategy));
}
NamingStrategy = strategy;
}
public override void WriteJson (JsonWriter writer, JObject value, JsonSerializer serializer) {
writer.WriteStartObject ();
foreach (JProperty property in value.Properties ()) {
var name = NamingStrategy.GetPropertyName (property.Name, false);
writer.WritePropertyName (name);
serializer.Serialize (writer, property.Value);
}
writer.WriteEndObject ();
}
public override JObject ReadJson (JsonReader reader, Type objectType, JObject existingValue, bool hasExistingValue, JsonSerializer serializer) {
throw new NotImplementedException ();
}
}
Usage
var snakeNameStrategy = new SnakeCaseNamingStrategy ();
var jsonSnakeSettings = new JsonSerializerSettings {
Formatting = Formatting.Indented,
Converters = new { new JObjectNamingStrategyConverter (snakeNameStrategy) },
ContractResolver = new DefaultContractResolver {
NamingStrategy = snakeNameStrategy
},
};
var json = JsonConvert.SerializeObject (obj, jsonSnakeSettings);
You can find a working PoC on GitHub.
A solution that well integrates with NewtonSoft framework is to provide a custom JObject converter that honours the NamingStrategy
.
JObject Custom Converter
public class JObjectNamingStrategyConverter : JsonConverter<JObject> {
private NamingStrategy NamingStrategy { get; }
public JObjectNamingStrategyConverter (NamingStrategy strategy) {
if (strategy == null) {
throw new ArgumentNullException (nameof (strategy));
}
NamingStrategy = strategy;
}
public override void WriteJson (JsonWriter writer, JObject value, JsonSerializer serializer) {
writer.WriteStartObject ();
foreach (JProperty property in value.Properties ()) {
var name = NamingStrategy.GetPropertyName (property.Name, false);
writer.WritePropertyName (name);
serializer.Serialize (writer, property.Value);
}
writer.WriteEndObject ();
}
public override JObject ReadJson (JsonReader reader, Type objectType, JObject existingValue, bool hasExistingValue, JsonSerializer serializer) {
throw new NotImplementedException ();
}
}
Usage
var snakeNameStrategy = new SnakeCaseNamingStrategy ();
var jsonSnakeSettings = new JsonSerializerSettings {
Formatting = Formatting.Indented,
Converters = new { new JObjectNamingStrategyConverter (snakeNameStrategy) },
ContractResolver = new DefaultContractResolver {
NamingStrategy = snakeNameStrategy
},
};
var json = JsonConvert.SerializeObject (obj, jsonSnakeSettings);
You can find a working PoC on GitHub.
answered Jul 10 at 18:41
Lord of the Goo
537620
537620
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f40244395%2fhow-to-serialize-a-jobject-the-same-way-as-an-object-with-json-net%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Doesn't
JObject
have aToString
method that returns JSON?– Heretic Monkey
Oct 25 '16 at 16:30
I don't think you can "edit" a
JObject
during serialization withJsonConvert.SerializObject()
. AJObject
has already been serialized so allJsonConvert
is doing is emit it more-or-less verbatim. See Newtonsoft Json.Net serialize JObject doesn't ignore nulls, even with the right settings. For a workaround see JSON.NET serialize JObject while ignoring null properties,– dbc
Oct 25 '16 at 17:12
@MikeMcCaughan JObject.ToString converts the object to json, but doesn't have any overload to accept the settings object.
– Natan
Oct 25 '16 at 18:32