Panic
Panic

Reputation: 335

How to ignore JsonPropertyNameAttribute annotation when serialize object?

I want to deserialize JSON from other guys API which uses different naming policy, so I add JsonPropertyNameAttribute to POCO

public class X
{
  [JsonPropertyNameAttribute("uid")]
  public string Name {get;set;}
}

and it expected it to be serialized to

{
  "name" : xx,
  .....
}

or

{ 
  "Name" : xx,
  .....
}

not

{
  "uid" : xx,
  ......
}

How to do it with System.Text.Json gracefully?
(except creating new POCO like X without annotation)

Upvotes: 2

Views: 702

Answers (1)

Alexander Petrov
Alexander Petrov

Reputation: 14231

Define your model without JsonPropertyNameAttribute

public class X
{
    public string Name { get; set; }
}

Create cutsom policy

public class DeserializePolicy : JsonNamingPolicy
{
    public override string ConvertName(string name)
        => name == "Name" ? "uid" : name;
}

Use it to deserialize

string text = "{\"uid\":\"abc\"}";

var options = new JsonSerializerOptions { PropertyNamingPolicy = new DeserializePolicy() };

var x = JsonSerializer.Deserialize<X>(text, options);

Serialize without policy

var json = JsonSerializer.Serialize<X>(x);

I'm not sure if this can be considered gracefully.

Upvotes: 4

Related Questions