Home > Back-end >  Trouble figuring out how to make a proper request based on another API
Trouble figuring out how to make a proper request based on another API

Time:12-29

I'm having some trouble creating a request.

There is an another API that have a request pattern like this:

{
  "someNumber":"111222333",
   "theList":{
     "0":"1233",
     "1":"2333"          
   },
  "something":"thisThing"
}

My trouble is with theList. How can I simulate those indexes on the request at my API? What I did was the following:

public class Item
{
    [JsonProperty("someNumber")]
    public long Number{ get; set; }
    [JsonProperty("theList")]
    public List<string> NumberList{ get; set; }
    [JsonProperty("something")]
    public string Something{ get; set; }
}

But this is obviously not correct, what is the best way to simulate what was done in the other API?

CodePudding user response:

The json structure for theList can be deserialized into a Dictionary<string,string>:

public class Item
{
    [JsonProperty("someNumber")]
    public long Number{ get; set; }

    [JsonProperty("theList")]
    public Dictionary<string, string> NumberList{ get; set; }

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

Demo


If the keys and values in theList are always numbers, and since you're using Netwontoft.Json, you could also deserialize straight into Dictionary<int, int>, Dictionary<int, long>, Dictionary<string, long>, etc. However, this won't work in System.Text.Json.

  • Related