4

Sorry for the (maybe) trivial question but, I'm trying to consume a web service where the entities and my data model classes are named different.

I want to keep my model .Net Class name and use a Json Attribute name to map, serializer/deserializer, with the corresponding web service entity. For example:

Web Service Entity:

"People"

My Model Class:

"Employee"

What I've already do:

[JsonObject(Title="People")]
public class Employee 
{

   [JsonProperty("DifferentPropertyName")]
   string propertyName1 { get; set; }
}

But the json serializer/Deserializer continues to use the .Net class name and I need to set the jsonObject Title.

There is a way to achieve it?

EDIT

I'm working on a Xamarin Forms app, using Simple.OData.Client to consume an OData Service

Thanks

Richard
  • 128
  • 2
  • 3
  • 10
  • Maybe this will help : http://stackoverflow.com/questions/13839426/how-can-i-add-a-custom-root-node-when-serializing-an-object-with-json-net – Yanga Nov 25 '16 at 15:40
  • Maybe this can help: `[JsonProperty(Title="People")] public string propertyName1{get; set;}` – Mario Galván Nov 25 '16 at 18:31
  • Please show serialization/deserialization code that is doing the wrong thing. – DavidS Nov 25 '16 at 18:46
  • Thanks... The problem is not with the properties but with the class name. As I'm using the simple.odata.client nuget package I'm trying to deserialize a resource entity that is named "People" into a .net class (model) named "Employee". At this point the simple.odata.client looks for a service resource (entity) named "Employee" that can't be found. – Richard Nov 25 '16 at 19:05
  • Have you tried serializing to JSON string first then deserializing that string into you Employee class? Might not be good for performance but it's a workaround. – Christian Melendez Nov 26 '16 at 15:50

1 Answers1

3

DataContractAttribute may be your solution.

public class RichFilter
{
   public Trolo item { get; set; }
}
[DataContract(Name = "item")]
public class Trolo 
{ 
   public string connector { get; set; } 
}

If you serialize a RichFilter object, here is the output :

{"item":{"connector":"AND"}}
Thibault
  • 446
  • 7
  • 17
  • 2
    When using the `DataContractAttribute` you **must** also specify the `DataMemberAttribute` on [properties you want to serialize](https://www.newtonsoft.com/json/help/html/DataContractAndDataMember.htm). – Erik Philips Aug 08 '18 at 23:28
  • Since I was using Simple.OData.Client, that is not able to recognize the DataContract attribute, I had to pass the name of my remote element explicitly. I, anyway, used a custom attribute like "ClassName" with a property that returns the name of the class but this is too much work for its purpose. – Richard Sep 23 '18 at 14:39