Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Property mapping in RestSharp for JSON doesn't work

I have such code:

using System;
using RestSharp.Serializers;

public class Program
{
    public static void Main()
    {
        var obj = new Order();
        obj.Test = 42;
        var serializer = new JsonSerializer();
        var json = serializer.Serialize(obj);
        Console.WriteLine(json);    
    }
}

public class Order
{
    [SerializeAs(Name = "object")]
    public string Object
    {
        get { return "Order"; }
    }

    [SerializeAs(Name = "TestName")]
    public int Test
    {
        get;set;
    }           
}

Based on SerializeAs attribute, RestSharp should use names from attribute, not the property name. But it just ignores it. Output for this code is:

{
  "Object": "Order",
  "Test": 42
}

Am I missed something or it doesn't work with RestSharp?

The same code snippet in DotNetFiddle - http://dotnetfiddle.net/ffaXUY

like image 695
Sergey Litvinov Avatar asked Feb 28 '14 16:02

Sergey Litvinov


Video Answer


2 Answers

According to this resource:

RestSharp has decided to bring back Newtonsoft.JSON support in v107.0.

So, if you are using a RestSharp 107+, you can safely use JsonPropertyAttribute attribute to specify property mapping. This is especially useful when dealing with APIs using another naming convention (e.g. snake case).

Related.

like image 114
Alexei - check Codidact Avatar answered Oct 11 '22 07:10

Alexei - check Codidact


Well, RestSharp uses SimpleJson, that hasn't any reference to SerializeAs and it also hasn't own mechanism for it. I found a pull request - https://github.com/restsharp/RestSharp/pull/331 , but it was closed because of SimpleJson.

In default implementation of IJsonSerializerStrategy - PocoJsonSerializerStrategy there is some initial logic to do property name replacing, but it doesn't work for now. It has such method - https://github.com/facebook-csharp-sdk/simple-json/blob/master/src/SimpleJson/SimpleJson.cs:

protected virtual string MapClrMemberNameToJsonFieldName(string clrPropertyName)
{
    return clrPropertyName;
}

So i just replaced SimpleJson to Newtonsoft Json based on the sample from this article - http://blog.patrickmriley.net/2014/02/restsharp-using-jsonnet-serializer.html

like image 23
Sergey Litvinov Avatar answered Oct 11 '22 06:10

Sergey Litvinov