How to get JSON response same as the property name?

Viewed 34

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"
}
1 Answers

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"}
Related