-2

I have my Response model class below.

using System.Text.Json.Serialization;

public class Response
{
    [JsonPropertyName("PFUserID")]
    public string UserId { get; set; }
}

I am using JsonSerializer.Deserialize<Response>(jsonHelperResponse); to get the deserialized response, and my jsonHelperResponse contains PFUserID.

But, because of this, my JSON response is,

{
  "PFUserID": "string"
}

I want it to return

{
  "UserId": "string"
}
tRuEsAtM
  • 3,517
  • 6
  • 43
  • 83
  • A bit unclear. Do you mean that you want to deserialize with one property name, but serialize with a different name? – Rotem Sep 05 '22 at 18:48
  • Check this https://stackoverflow.com/questions/44632448/use-different-name-for-serializing-and-deserializing-with-json-net – Andrii Khomiak Sep 05 '22 at 18:50
  • 2
    The easiest option - create another class with the same fields, map data to it and serialize it. – Guru Stron Sep 05 '22 at 18:50
  • @Rotem Yeah, that's correct. – tRuEsAtM Sep 05 '22 at 18:51
  • You will need to use a DTO or custom `JsonConverter` (or both if you define the DTO inside the converter). In Json.NET you could use a custom contract resolver to override the name but System.Text.Json does not make its contract information public, see [System.Text.Json API is there something like IContractResolver](https://stackoverflow.com/q/58926112/3744182) for confirmation. – dbc Sep 05 '22 at 19:16
  • @AndriiKhomiak - Querent is using System.Text.Json not Json.NET. – dbc Sep 05 '22 at 19:18

1 Answers1

0

You can write a custom JsonConverter<T> with System.Text.Json to do this:

Decorate your class with the converter:

[JsonConverter(typeof(ResponseConverter))]
public class Response
{
    public string UserId { get; set; }
}

(or if you don't want to pollute your class with attributes, add the converter to an instance of JsonSerializerOptions.)

Implement the converter:

public class ResponseConverter : JsonConverter<Response>
{
    public override Response? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        if (reader.TokenType != JsonTokenType.StartObject)
            throw new JsonException();

        var response = new Response();

        while (reader.Read())
        {
            if (reader.TokenType == JsonTokenType.EndObject)
                return response;

            if (reader.TokenType != JsonTokenType.PropertyName)
                throw new JsonException();

            string? propertyName = reader.GetString();
            reader.Read();
            switch (propertyName)
            {
                case "PFUserID":
                    response.UserId = reader.GetString();
                    break;
            }
        }

        throw new JsonException("Ran out of JSON to read before the object ended.");
    }

    public override void Write(Utf8JsonWriter writer, Response value, JsonSerializerOptions options)
    {
        writer.WriteStartObject();

        writer.WriteString("UserId", value.UserId);

        writer.WriteEndObject();
    }
}

So you can now read PFUserID from incoming JSON, and write UserId to outgoing JSON:

string jsonHelperResponse = @"{""PFUserID"": ""string""}";

Response deserialized = JsonSerializer.Deserialize<Response>(jsonHelperResponse);

Debug.Assert("string" == deserialized.UserId);

string serialized = JsonSerializer.Serialize(deserialized);
// {"UserId":"string"}
Jason Weinzierl
  • 342
  • 1
  • 6
  • 12