I want to iterate through my JSON response in viewmodel MVC so I am trying to incorporate IEnumerable for this:
ArtistInfoResponse IMusicRepository.GetArtistResponse(string artistName)
{
artistName = (char)34 + artistName + (char)34;
RestClient client = new RestClient($"https://api.deezer.com/search?q=artist:{artistName}");
RestRequest request = new RestRequest(Method.GET);
IRestResponse response = client.Execute(request);
if (response.IsSuccessful)
{
// Deserialize the string content into JToken object
var content = JsonConvert.DeserializeObject<JToken>(response.Content);
// Deserialize the JToken object into our ArtistInfoResponse Class
return content.ToObject<ArtistInfoResponse>();
}
return null;
}
And I get this response:
From this Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'MyMusicApp.Models.ArtistInfoResponse' 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<T>) 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 'data'.'
Here is my class:
public class ArtistInfoResponse : IEnumerable
{
public SongInfo[] Data { get; set; }
public int Total { get; set; }
public string Next { get; set; }
public IEnumerator GetEnumerator()
{
throw new NotImplementedException();
}
}
The response itself is an object and not an array. You should not implement IEnumerable for your ArtistInfoResponse class. The response only contains an array for data wich you have implemented correctly as SongInfo[].
EDIT: Here ist an example request for anyone who comes here:
https://api.deezer.com/search?q=artist:dire%20straits
Related
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.
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";
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);
I'm working on Xamarin App, where I'm trying to get the Json data from the server, and it's working fine.
But, now I just want to read/view the value of "invitation".
Json Value:
{"invitation":"http://example.com?c_i=eyJsYWJlbCI6Iklzc3VlciIsImltYWdlVXJsIjpudWxsLCJzZXJ2aWNlRW5kcG9pbnQiOiJodHRwOi8vNTIuNzcuMjI4LjIzNDo3MDAwIiwicm91dGluZ0tleXMiOlsiSE51N0x6MkxoZktONEZEMzM2cWdDNWticWI0dTZWRkt2NERaano4YWc1eHQiXSwicmVjaXBpZW50S2V5cyI6WyI3Sm1MMVhOSHRqSHB2WW1KS3d0ZXM2djltNk5yVUJoZW1ON3J6TnZLcGN0SyJdLCJAaWQiOiIzZjgyNWRkZC0zNjNhLTQ2YzEtYTAxNi0xMjAwY2FhZjRkNTkiLCJAdHlwZSI6ImRpZDpzb3Y6QnpDYnNOWWhNcmpIaXFaRFRVQVNIZztzcGVjL2Nvbm5lY3Rpb25zLzEuMC9pbnZpdGF0aW9uIn0="}
I'm getting this error... don't know why?
Error Message:
Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Osma.Mobile.App.ViewModels.Index.IndexViewModel+RootObject]' 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<T>) 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 'invitation', line 1, position 14.'
The
Code I wrote.....
Class:
public class ConnectionJson
{
public string Invitation { get; set; }
}
public class RootObject
{
public List<ConnectionJson> ConnectionsJson { get; set; }
}
Main Code :
public async Task<List<RootObject>> ConnectionInvitationJson()
{
HttpClient hTTPClient = new HttpClient();
Uri uri = new Uri(string.Format("http://example.com/Connections/CreateInvitationJson"));
HttpResponseMessage response = await hTTPClient.GetAsync(uri);
string content = await response.Content.ReadAsStringAsync();
var Items = JsonConvert.DeserializeObject<List<RootObject>>(content);
await DialogService.AlertAsync(Items.ToString(), "Connection Invitation Json", "Ok");
return Items;
}
Your Json is just a single object. Update the code as below
var json = JsonConvert.DeserializeObject<ConnectionJson>(content);
After updating the code you can modify the logic as below if you don't want to change the classes structure
var Items = new List<RootObject> { new List<ConnectionJson> { json }};
I'm trying to convert a FeedResponse into List but failing to serialize the string as it throws an error
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Lutran.Api.Models.Infinity]' 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 'token', line 1, position 9.
I have used the logic for pagination using the this link and getting the data when returning the entire output object but when im trying to convert it fails.Tried using an ienumerable object but it shows type conversion error.Used a dynamic object but cannot extract ResponseContinuation value from it.
Using Newton Soft to convert the json(deserialize the string)
var query = client.CreateDocumentQuery<Document>(collection, options).AsDocumentQuery();
if (query.HasMoreResults)
{
var result = await query.ExecuteNextAsync<LeadDataView>();
objLeadDataView.ResponseContinuation = result.ResponseContinuation;
objLeadDataView.InfinityDataView = JsonConvert.DeserializeObject<List<Infinity>>(result.ToString());
response = objLeadDataView;
}
I Figured it out
public class LeadDataView
{
public string ResponseContinuation { get; set; }
public FeedResponse<Infinity> InfinityDataView { get; set; }
}
if (query.HasMoreResults)
{
var result = await query.ExecuteNextAsync<Infinity>();
objLeadDataView.ResponseContinuation = result.ResponseContinuation;
objLeadDataView.InfinityDataView = result;
response = objLeadDataView;
}
So the above code sent the continuation token on top and infinity class data below.enter image description here
I am having an issue I have been researching and can not seem to figure out. I am trying to deserialize Json return from a restsharp call to an api. It worked great on my first one where there was not an array involved. Now that I am trying to do it on a string with an array in it I am having issues. If anybody could help me figure this out it would be greatly appreciated, thank you in advance.
So I am trying to get Roles to be stored to my Model, but it fails because it is an array:
Here is my method:
var request = new RestRequest("api/user/{id}", Method.GET);
request.AddUrlSegment("id", id);
var response = client.Execute(request) as RestResponse;
var d = JsonConvert.DeserializeObject<List<MyModel>>(response.Content);
The error I am getting is on the above line at var d = .... It says:
Cannot implicitly convert type
'System.Collections.Generic.List<Models.MyModel>' to 'Models.MyModel'
The response for var response is (trying to get Roles stored in d to store in model):
"{\"Id\":22,\"FirstName\":\"Shawn\",\"LastName\":\"John\",\"Roles\":[\"User\"]}"
My MyModel looks like so:
public class MyModel
{
public string Id { get; set; }
public string Roles { get; set; }
}
Updated code
Getting this error now on the same line:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type
'System.Collections.Generic.List`1[Models.MyModel]' 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<T>) 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.
Changed model to be :
public List<MyModel> Roles { get; set; }
and controller variable to :
List<MyModel> deSerialize2 =
JsonConvert.DeserializeObject<List<MyModel>>(response.Content);
try changing your model to
public class MyModel
{
public int Id { get; set; }
public List<string> Roles { get; set; }
}
Roles is an array of strings.
Edit: After further inspection, id is actually an integer not a string.
Also, change your deserialize call to this
var d = JsonConvert.DeserializeObject<MyModel>(response.Content);
The json response isn't an array.
plz help, I'm stuck.
I have a WCF service which returns something like this:
{
"GetDataRESTResult":
[
{"Key1":100.0000,"Key2":1,"Key3":"Min"},
{"Key1":100.0000,"Key2":2,"Key3":"Max"}
]
}
and I would like to deserialize it, but whatever I use (JSON.NET or DataContractJsonSerializer) I'm getting errors.
When using DataContractJsonSerializer I'm using theis code:
byte[] data = Encoding.UTF8.GetBytes(e.Result);
MemoryStream memStream = new MemoryStream(data);
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<DataDC>));
List<DataDC> pricinglist = (List<DataDC>)serializer.ReadObject(memStream);
where DataDC is the data contract which I've got from the service reference of the WCF REST service I'm getting the JSON data from, and the error I'm getting is InvalidCastException...
Trying to use JSON.NET I get another exception, but still nothing I can figure out, can anyone help please?
EDIT
Here's a JSON.NET stacktrace:
Cannot deserialize the current JSON object (e.g. {"name":"value"})
into type
'System.Collections.Generic.List`1[MyApp.MyServiceReference.DataDC]'
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 'GetDataRESTResult', line 1,
position 23.
{"GetDataRESTResult":[{"Key1":100.0000,"Key2":1,"Key3":"Min"},{"Key1":100.0000,"Key2":2,"Key3":"Max"}]}
You data is a JSON object (where it has one key 'GetDataRESTResult' with a JSON array as the value). Because of that, the type you should deserialize into should be an object, not a collection.
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(DataDC));
DataDC pricinglist = (DataDC)serializer.ReadObject(memStream);
It will work if your type DataDC look something like this:
public class DataDC
{
public List<Keys> GetDataRESTResult { get; set; }
}
public class Keys
{
public double Key1 { get; set; }
public int Key2 { get; set; }
public string Key3 { get; set; }
}
Below code works
string json = #" {""GetDataRESTResult"":[{""Key1"":100.0000,""Key2"":1,""Key3"":""Min""},{""Key1"":100.0000,""Key2"":2,""Key3"":""Max""}]}";
dynamic dynObj = JsonConvert.DeserializeObject(json);
foreach (var item in dynObj.GetDataRESTResult)
{
Console.WriteLine("{0} {1} {2}", item.Key1, item.Key3, item.Key3);
}
You can also use Linq
var jObj = (JObject)JsonConvert.DeserializeObject(json);
var result = jObj["GetDataRESTResult"]
.Select(item => new
{
Key1 = (double)item["Key1"],
Key2 = (int)item["Key2"],
Key3 = (string)item["Key3"],
})
.ToList();