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
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 have a class which contains the ocject DateTime.
public class Refuel
{
public DateTime DateTime { get; set; }
public string Litre { get; set; }
}
When deserializing my text file I get an error.
Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[OD_TankApp.Models.Refueling]' 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 'DateTime', line 1, position 12.
I tried already with Json settings but it didnt helped.
JsonSerializerSettings settings = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat};
this is the json string:
"{\"DateTime\":\"2019-02-28T16:21:06.36845+01:00\",\"Litre\":\"23\"}}"
You are trying to deserialize a json string which represents a single object into a list/array of objects which will not work. Either deserialize it into a single object like this:
var obj = JsonConvert.DeserializeObject<Refuel>(json);
Or change your json string to contain a list of objects:
"[{\"DateTime\":\"2019-02-28T16:21:06.36845+01:00\",\"Litre\":\"23\"}]"
Now you can deserialize it like that:
var objArray = JsonConvert.DeserializeObject<Refuel[]>(json);
If you want to deserialize an array, you'll need to secify that ([])
JsonConvert.DeserializeObject<Refuel[]>(json);
I want to deserialize json into collection of C# objects but getting following error:
{"Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'System.Collections.Generic.List`1 because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.\r\nTo 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.\r\nPath 'organizations', line 1, position 17."}
Code:
var jSon = "{\"Houses\":[{\"id\":\"123\",\"doorNumber\":22},
{\"id\":\"456\",\"deniNumber\":99}
]}";
var temp = JsonConvert.DeserializeObject<List<House>>(jSon);
}
public class House
{
public int Id { get; set; }
public int DoorNumber { get; set; }
}
The JSON you've shown is an Object with a Property called Houses that contains your array. Note how the outer Json is surrounded by { } and not [ ] which is why you're seeing that error. You'll need to select only the value of that property if you want to deserialize to a list of House. You can do that using JObject and then selecting the Houses property specifically.
var jobj = JObject.Parse(jSon);
var houses = JsonConvert.DeserializeObject<List<House>>(jobj["Houses"].ToString());
Alternatively you could do:
var houses = JObject.Parse(jSon)["Houses"].ToObject<List<House>>();
If you want to be able to map it in one step without using JObject you'd have to have another class that wraps your House list and maps directly to the JSON you've shown.
public class HouseList
{
public List<House> Houses {get; set;}
}
Given this object you'd be able to do
var houses = JsonConvert.DeserializeObject<HouseList>(jSon).Houses;
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.