Home > Net >  Json convert array string to object is null
Json convert array string to object is null

Time:10-08

I am having trouble converting my JSON result. I am getting a http response and I am unable to convert it to an object. I have tried changing the Token class into arrays and list types, but no luck. I am using .NET 6.0 Web Api. Thanks in advance!

public class Tokens
{
  public string Token { get; set; }
}
var x = await response.Content.ReadAsStringAsync();

// value of x is "{\"tokens\":[\"6856\",\"d70f1\",\"c66b\",\"45b\",\"3090\",\"8ac68\",\"fsf28\"]}"

var token = JsonConvert.DeserializeObject<Tokens>(x);
// token is null

I have also tried:

var token = JsonConvert.DeserializeObject<List<Tokens>>(x);

But I get the following error:

Error: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[...Tokens]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly. To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. Path 'tokens', line 1, position 10.

CodePudding user response:

you don't need any custom class, just parse your response

string x = "{\"tokens\":[\"6856\",\"d70f1\",\"c66b\",\"45b\",\"3090\",\"8ac68\",\"fsf28\"]}";
    
List<string> tokens = JObject.Parse(x)["tokens"].ToObject<List<string>>();

in this case you can acces to each of string separately

var x = tokens[0];
var y = tokens[1];
// etc

or if you need all of them in one string, according to your class

string token = string.Join(",", JObject.Parse(x)["tokens"].ToObject<string[]>());

//result "6856,d70f1,c66b,45b,3090,8ac68,fsf28";

//or more probably
string token = string.Join("", JObject.Parse(x)["tokens"].ToObject<string[]>());

//result "6856d70f1c66b45b30908ac68fsf28";

CodePudding user response:

Your Json string has an array of string, your model only has a string. This is why the deserialisation failing.

Change

public class Tokens
{
  public string Token { get; set; }
}

To

public class Tokens
{
  public IEnumerable<string> Tokens { get; set; }
}

Or you can deserialise using the following statement

var token = JsonConvert.DeserializeObject<IEnumerable<Tokens>>(x);
  • Related