0

Suppose I have some class that defines ToString():

class Person {
  public override string ToString() { /* ... */ }
}

And suppose an instance is contained in some model:

public Person Person { get; }

Then it is serialized like this:

"person": {
  "value": "Foo Bar"
}

But what I expected was this:

"person": "Foo Bar"

Can I do this somehow, or must I use a custom converter?


UPDATE

No this is not a dupe of that linked question. That shows how to do two-way conversion to/from a type. I want to do one-way conversion, given my type already has a ToString method - i.e. serialization only, not deserialization.

The question is not how to write a type converter - it is whether this one-way serialization is possible without a type converter.

lonix
  • 14,255
  • 23
  • 85
  • 176
  • 1
    Looks like a duplicate of [Json.Net: Serialize/Deserialize property as a value, not as an object](https://stackoverflow.com/q/40480489/3744182), agree? – dbc Jun 14 '19 at 09:11
  • @dbc Not a dupe, see update. – lonix Jun 14 '19 at 12:53

2 Answers2

1

I recently ran into this on a project, and the only thing my team came to, was having to write a type converter.

ddeamaral
  • 1,403
  • 2
  • 28
  • 43
0

I want a one-way conversion which relies on my type's ToString() overload. This is for data serialized on the server and used in a REST response.

This is what I did:

public class StringConverter : JsonConverter {

  public override bool CanConvert(Type objectType) {
    return true;
  }

  public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {
    throw new NotSupportedException("This one-way converter cannot be used for deserialization.");
  }

  public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) {
    writer.WriteValue(value.ToString());
  }

}

Used like this:

[JsonConverter(typeof(StringConverter))]
public Person Person { get; }   // assumes Person has overloaded ToString()

And the serialized result is this:

"person": "Foo Bar"

(instead of "person": { "value": "Foo Bar" }.)

Maybe a better name is ToStringSerializer or OneWayStringConverter.

lonix
  • 14,255
  • 23
  • 85
  • 176