Domanda

I am trying to serialize a list over a RestSharp request. I am getting the correct number of items returned in the list, but their values are all blank. I've tried a lot of different attempts of Json annotations at JsonConvert, but this is the closest I have to working.

public string updateRewards(List<Reward> rewards)
{
        RestRequest request = new RestRequest(updateRewardsUrl, Method.POST);
        request.RequestFormat = DataFormat.Json;
        request.AddParameter("rewards", JsonConvert.SerializeObject(rewards));
        RestResponse response = (RestResponse)client.Execute(request);
 ...
}

[JsonObject]
public class Reward
{
    [JsonProperty("id")]
    public int id { get; set; }

    [JsonProperty("reward")]
    public string reward { get; set; }

    [JsonProperty("title")]
    public string title { get; set; }
}

On the other endpoint...

public object Post(UpdateRewardsRequestDTO updateRewardsRequest)
{
 ...handle request...
}

[Route("/Rewards/updateRewards", "POST")]
public class UpdateRewardsRequestDTO : IReturn<UpdateRewardsResponseDTO>
{
    public List<Reward> rewards { get; set; } //different Reward class, but exact same code as above
}

Sample RestRequest parameters

-   System.Collections.Generic.List<RestSharp.Parameter>
+       [0] {rewards=[{"id":0,"reward":"test","title":"test2"}]}    RestSharp.Parameter

Sample request received on the other endpoint

-       updateRewardsRequest    
-       rewards Count = 1   
-       [0] 
        id  0   int
        reward  null    string
        title   null    string

Could the problem be that two different instances of Reward are causing it to be unable to convert from one to the other?

È stato utile?

Soluzione

I managed to get it working with a little hack.

The code on the first endpoint remains the same; the list of rewards is serialized using JsonConvert.SerializeObject(rewards).

On the second endpoint, I define the type of the rewards as a string instead of a List<Reward>. It shows up as an escaped json string. From there, I explicitly use JsonConvert.DeserializeObject<List<Reward>>(rewards) to convert into the list.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top