Home > Software design >  JsonConvert.DeserializeObect() method not working when mapping to my classes
JsonConvert.DeserializeObect() method not working when mapping to my classes

Time:02-17

I'm currently trying to map a jsonstring (from an API) to a class I created but I'm having trouble mapping to my classes. Here is what I have.

API Response:

var resultContent = response.Content.ReadAsStringAsync().Result?.ToJsonString();
        if (resultContent != null)
        {
            result = JsonConvert.DeserializeObject<LastYearSearchResultPayload>(resultContent).JsonData;
        }

Class Objects:

public class LastYearSearchResults
{
    [JsonProperty("final_score")]
    public List<double> FinalScore { get; set; }
    [JsonProperty("item1_desc")]
    public List<string> ItemDescription { get; set; }
    [JsonProperty("item_nbr")]
    public List<int> ItemNumber { get; set; }
    [JsonProperty("prod_desc")]
    public List<string> ProductDescription { get; set; }
    [JsonProperty("qte_id")]
    public List<int> QuoteId { get; set; }
    [JsonProperty("vendor_name")]
    public List<string> VendorName { get; set; }
    [JsonProperty("vendor_nbr")]
    public List<int> VendorNumber { get; set; }
}

public class meta
{

}

public class LastYearSearchResultPayload
{
    [JsonProperty("jsonData")]
    public LastYearSearchResults JsonData { get; set; }
    [JsonProperty("meta")]
    public meta Meta { get; set; }
}

JsonString Im trying to convert:

"{"jsonData":{"final_score":[0.95],"item1_desc":["TOOL"],"item_nbr":[586203342],"prod_desc":["Air Cut Off Tool"],"qte_id":[12345],"vendor_name":["IMPORT"],"vendor_nbr":[62735]},"meta":{}}\n"

CodePudding user response:

Thank you. The ?.ToJsonString() messing with my result it was placed there for some other implementation.

CodePudding user response:

I usually install ResSharp nuget package to get the response with different options as: response.StatusCode, response.IsSuccessful, etc. And for mapping the response:

var jsonSerializer = new JsonSerializer();
return jsonSerializer.Deserialize<Your_Object>(response);

JsonSerializer is included in ResSharp nuget package. Hope it helps in future tasks!

  • Related