Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unexpected behavior when using a converter with a nested serializer #3006

Open
codemonkey493 opened this issue Dec 19, 2024 · 2 comments
Open

Comments

@codemonkey493
Copy link

Source/destination types

I'm serializing an array of MyInfo objects using the following converter, with JSON serializer formatting set to indented:

class TestConverter : JsonConverter<MyInfo>
{
	public override void WriteJson(JsonWriter writer, MyInfo value, JsonSerializer serializer)
	{
		var subSerializer = new JsonSerializer
		{
			Formatting = Formatting.None,
		};
		subSerializer.Serialize(writer, new Dictionary<string, string> { { "Name", value.Name } });
	}

	public override MyInfo ReadJson(JsonReader reader, Type objectType, MyInfo existingValue, bool hasExistingValue, JsonSerializer serializer)
	{
		throw new NotSupportedException();
	}
}

class MyInfo
{
	public string Name;
}

Expected behavior

I expected that it would use the nested serializer to serialize the values of the objects only, so the result would look like this:

[
    {"Name":"SomeName1"},
    {"Name":"SomeName2"}
]

Actual behavior

However, it looks like this:

[{"Name":"SomeName1"},{"Name":"SomeName2"}]

What am I missing?

@codemonkey493
Copy link
Author

codemonkey493 commented Dec 19, 2024

PS when I do conversion like this, it works as expected:

var text = JsonConvert.SerializeObject(new Dictionary<string, string> { { "Name", value.Name } });
writer.WriteRawValue(text);

I wonder why the code with the nested serializer doesn't?

@ddev10d
Copy link

ddev10d commented Jan 3, 2025

Hi @codemonkey493 , You can use Formatting = Formatting.Indented to indent the formatting of the serialized objects.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants