1

I have:

class TableEntity
{
    public string PartitionKey {get; set;}
    public string RowKey {get; set;}
}

class MyEntity : TableEntity
{
    [JsonProperty(PropertyName = "myAFieldName")]
    public string AField {get; set;}
}

TableEntity is part of an external library, I cannot add attributes to it.

I want to set the JsonProperty of the PartitionKey & RowKey to: "GroupID" & "ItemID", in part to hide the implementation from being exposed through JSON.

How can I do this?

Tim
  • 514
  • 8
  • 17
  • The question is quite different (I am trying to rename fields brought in through inheritance, not hide fields of a 3rd party class I am serializing). But, yes, it does appear that the same solution would apply. I'll upvote both answers below, as they are solutions. But ultimately I think I will go with the solution in the other question: http://stackoverflow.com/a/25769147/1118474 – Tim Feb 01 '16 at 17:48

2 Answers2

2

Generally speaking, it is easier to just convert your entities to a proper view model (I almost never pass a raw entity to JSON/views). If this sample is only part of your object and there are actually some properties that would match names to the VM definition, then you could use AutoMapper to make populating the VMs easier. If none of the properties match, its practically easier to just give your VM a constructor that takes your entity and assigns the values to its properties.

public class MyEntityVM
{
    public MyEntityVM(MyEntity entity)
    {
        this.ItemId = entity.RowKey;
        //etc...
    }
    public string ItemId {get;set;}
    public string GroupId {get;set;}
    public string MyAFieldName {get;set;
}
solidau
  • 4,021
  • 3
  • 24
  • 45
1

Did you try to use MetadataTypeAttribute (https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.metadatatypeattribute(v=vs.110).aspx)?

class TableEntity
{
    public string PartitionKey {get; set;}
    public string RowKey {get; set;}
}

[MetadataType(typeof(MyEntityMeta))]
class MyEntity : TableEntity
{
    public string AField {get; set;}
}

public class MyEntityMeta
{
    [JsonProperty(PropertyName = "GroupID")]
    public string PartitionKey {get; set;}

    [JsonProperty(PropertyName = "myAFieldName")]
    public string AField {get; set;}
}

See also: https://github.com/JamesNK/Newtonsoft.Json/issues/405

romanoza
  • 4,775
  • 3
  • 27
  • 44