0

I have a backend-service that calls a REST-Api. The result of that API is then deserialized into my entity:

public class Item {
  [JsonProperty("pkID")]
  public int Id {get;set;}
}

JsonConvert.DeserializeObject<Item>(responseString);

This works fine. But I also want to return the result as a JSON-string so I can use it from the Frontend. When now Serializing my object of Type "Item" using JsonConvert.SerializeObject(item) I want to return something like

{ Id: 1 }

Instead on serializing it also uses the JsonProperty and returns

{ pkID: 1 }

instead.

How can I tell the serializer to ignore the JsonProperty on serializing, but use it on deserializing?

I am NOT searching for a way whether the property should be serialized or not, but whether the propertyName should be used or the the name from the JsonProperty on serializing.

Ole Albers
  • 8,715
  • 10
  • 73
  • 166
  • In the question you linked it was about not serializing the property at all. I am asking for a way to keep the PropertyName instead – Ole Albers Aug 27 '19 at 09:37
  • @OleAlbers there is a pointer to `IContractResolver` which can help you to do this strange things that you are doing – vasily.sib Aug 27 '19 at 09:42
  • @vasily.sib I followed the description and AFAIK (I might be wrong here) it looks like this is about Serializing or not serializing the property and NOT what name the property should have. – Ole Albers Aug 27 '19 at 09:47
  • 2 more things to try: 1 - make your frontend to work with `pkID` instead of `Id`. 2 - create another class of your `Item` just for your frontend. – vasily.sib Aug 27 '19 at 09:51

2 Answers2

4

You could use a set-only property that points to the 'good' property.

public class Item
{
    public int Id { get; set; }

    [JsonProperty("pkID")]
    public int BackwardCompatibleId { set => Id = value; }
}

// test
var x = new Item { Id = 88 };
var json = JsonConvert.SerializeObject(x); // {"Id":88}
var clone = JsonConvert.DeserializeObject<Item>("{\"pkId\":99}");
sa.he
  • 1,391
  • 12
  • 25
  • While this does work the main reason I want to do this is to have "clean" code with Pascal-Casing as it should be and not having the REST-Interface forcing me to use "bad" naming – Ole Albers Aug 27 '19 at 10:10
  • 1
    Good point. I updated the answer using JsonPropertyAttribute as you did in the question. You could also try making 'BackwardCompatibleId' private to hide this 'hack' from other classes. – sa.he Aug 27 '19 at 11:10
1

you could use an own implementation of the ContractResolver.

here is an answer that could probably work: https://stackoverflow.com/a/20639697/5018895