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

long to string #2572

Open
DotNetNext opened this issue Aug 1, 2021 · 3 comments
Open

long to string #2572

DotNetNext opened this issue Aug 1, 2021 · 3 comments

Comments

@DotNetNext
Copy link

public long Id{get;set;}

What's the easiest way to do that

{id:"1231231313131"}

@elgonzo
Copy link

elgonzo commented Aug 2, 2021

Write a custom JsonConverter that converts a value to a string and writes the converted string value directly to the JsonWriter used by the serializer. The converter could possibly be as simple as:

public class ValueToStringConverter : JsonConverter
{
	public override bool CanRead => false;
	
	public override bool CanConvert(Type objectType) => objectType.IsValueType;
	
	public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		=> throw new NotSupportedException();
	
	public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
	{
		var str = value?.ToString();
		writer.WriteValue(str);
	}
}

Note that in this case the converter does not need to convert a string back to the original value type when deserializing/reading back the json data, hence why this converter sets CanRead to false. Newtonsoft.Json is flexible enough to convert a json string value to the respective value type all by itself.

dotnetfiddle demo: https://dotnetfiddle.net/MLeHLq

@DotNetNext
Copy link
Author

This is inconvenient, and the most basic functionality is not built-in

@JHeLiu
Copy link

JHeLiu commented Apr 16, 2023

He likes to configure this
opts.SerializerSettings.IsLongToString = true;
^_^

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

3 participants