Deserialize Json from array of strings

Viewed 32

I want my final response from API to look something like this:

{
    "someId" : [
        "12344",
        "fer33dw",
        "sdadadw23ed",
        "ljkljkj2"      
    ]
}

To do that I have created my ResponseDTO class to look like this:( which I might be wrong about)

public class ResponseDTO
{
    public List<string> someId { get; set; } = new List<string>();
}

Now imagine I have a List<string> of some values like this:

List<string> someValuesHere = new List<string>();
someValuesHere.Add("1234");  // etc....

So that someValuesHere is what I want to deserialzie and return as my response. So I did like this:

var result = JsonSerializer.Deserialize<ResponseDTO>(someValuesHere);

But this doesn't even compile. Error says "Non Generic Method Cannot be used with Type Arguments"

I am sure it is something stupid I have done wrong but can't see it myself.

1 Answers

you have to use this code, it was tested and working properly

var someValuesHere = new ResponseDTO
{
 someId= new List<string>()
};
someValuesHere.someId.Add("1234"); 

string json= System.Text.Json.JsonSerializer.Serialize(someValuesHere);
someValuesHere = System.Text.Json.JsonSerializer.Deserialize<ResponseDTO>(json); 
Related