Nick Heidke
Nick Heidke

Reputation: 2847

Unable to Deserialize JSON into Dictionary

I'm making an API call that returns JSON (into a variable called jsonString). Doing a Console.WriteLine(jsonString) on the JSON data reveals this:

{"contentType":null,"serializerSettings":null,"statusCode":null,"value":"{\"contentType\":null,\"serializerSettings\":null,\"statusCode\":null,\"value\":{\"10\":\"ALABAMA\",\"11\":\"ALASKA\",\"12\":\"ARIZONA\",\"13\":\"ARKANSAS\",\"14\":\"CALIFORNIA\",\"15\":\"COLORADO\",\"16\":\"CONNECTICUT\",\"17\":\"DELAWARE\",\"18\":\"FLORIDA\",\"19\":\"GEORGIA\",\"20\":\"HAWAII\",\"21\":\"IDAHO\",\"22\":\"ILLINOIS\",\"23\":\"INDIANA\",\"24\":\"IOWA\",\"25\":\"KANSAS\",\"26\":\"KENTUCKY\",\"27\":\"LOUISIANA\",\"28\":\"MAINE\",\"29\":\"MARYLAND\",\"30\":\"MASSACHUSETTS\",\"31\":\"MICHIGAN\",\"32\":\"MINNESOTA\",\"33\":\"MISSISSIPPI\",\"34\":\"MISSOURI\",\"35\":\"MONTANA\",\"36\":\"NEBRASKA\",\"37\":\"NEVADA\",\"38\":\"NEW HAMPSHIRE\",\"39\":\"NEW JERSEY\",\"40\":\"NEW MEXICO\",\"41\":\"NEW YORK\",\"42\":\"NORTH CAROLINA\",\"43\":\"NORTH DAKOTA\",\"44\":\"OHIO\",\"45\":\"OKLAHOMA\",\"46\":\"OREGON\",\"47\":\"PENNSYLVANIA\",\"48\":\"RHODE ISLAND\",\"49\":\"SOUTH CAROLINA\",\"50\":\"SOUTH DAKOTA\",\"51\":\"TENNESSEE\",\"52\":\"TEXAS\",\"53\":\"UTAH\",\"54\":\"VERMONT\",\"55\":\"VIRGINIA\",\"56\":\"WASHINGTON\",\"57\":\"WEST VIRGINIA\",\"58\":\"WISCONSIN\",\"59\":\"WYOMING\"}}"}

I'm attempting to deserialize it into a class that looks like this:

public class LookupValuesResponse
{
    [JsonProperty("value")]
    public Dictionary<int, string> LookupValues;

    [JsonProperty("statusCode")]
    public string Status;

}

I've tried this:

LookupValuesResponse lookupresponse = JsonConvert.DeserializeObject<LookupValuesResponse>(jsonString);

However, I get an error that the JSON cannot be deserialized:

System.ArgumentException : Could not cast or convert from System.String to System.Collections.Generic.Dictionary`2[System.Int32,System.String].

Upvotes: 0

Views: 303

Answers (1)

Nick Heidke
Nick Heidke

Reputation: 2847

I needed to change how the called API was returning its results. Previously I had:

return Ok(Json(response.Content.ReadAsStringAsync().Result));

instead I needed:

return Ok(JsonConvert.DeserializeObject(response.Content.ReadAsStringAsync().Result));

Upvotes: 0

Related Questions