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.
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 would like to start by saying that I am not a developer and this is my very first time writing a code to this extend of complication (at least to me). Any help/guidance would be much appreciated.
The idea of this program is to retrieve the employee user ID (or signature) from an API URL once the name has been entered.
I have a JSON String
[{"signature":"JDOW","firstName":"Jane","fullName":"Dow, Jane","lastName":"Dow"}]
I am trying to deserialize it to a collection. But I am getting an error. Can somebody direct me to the right way to fix this?
namespace TimeSheet_Try11_Models
{
public class Employeename
{
[JsonProperty("Signature")]
public string Signature { get; set; }
[JsonProperty("FirstName")]
public string FirstName { get; set; }
[JsonProperty("FullName")]
public string FullName { get; set; }
[JsonProperty("LastName")]
public string LastName { get; set; }
}
}
I a trying to convert using the following code:
uri = StaticStrings.UrlIora + name;
var response = wc.DownloadString(uri);
Employeename status = JsonConvert.DeserializeObject<Employeename>(response);
The error I am getting is:
Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'TimeSheet_Try11_Models.Employeename' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
Deserialize the Json data for collection as:
var status = JsonConvert.DeserializeObject<List<Employeename>>(response);
or
List<Employeename> status = JsonConvert.DeserializeObject<List<Employeename>>(response);
Another thing is that, no need to use attribute [JsonProperty("anyProperty")] with your properties. Json can be deserialized without using it in attributes.
After getting the deserialzed data in status object, any value can be fetched from that object as:
string signature = status.Select(js => js.Signature).First();
Similarly other values can also be taken from the status.
Your JSON string has square brackets ([]) around it, which means it is a collection of items.
This is why the Deserialiser is erroring.
You need to either remove those brackets to give just one employee object in the input string, or tell DeserializeObject that it is a List you are deserialising.
var converted = JsonConvert.DeserializeObject<List<Employeename>>(response);
Working Fiddle here
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
This might be a basic question but I am stuck while converting a JSON Response to a List.
I am getting the JSON Response as,
{"data":[{"ID":"1","Name":"ABC"},{"ID":"2","Name":"DEF"}]}
Have defined a Class,
class Details
{
public List<Company> data { get; set; }
}
class Company
{
public string ID { get; set; }
public string Name { get; set; }
}
Have tried this for converting,
List<Details> obj=List<Details>)JsonConvert.DeserializeObject
(responseString, typeof(List<Details>));
But this returns an error, saying
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Client.Details]' 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.
Kindly help!
You don't have a List<Detail> defined in your JSON. Your JSON defines one Detail record, which itself has a list of companies.
Just deserialize using Details as the type, not List<Details> (or, if possible, make the JSON wrap the single detail record into a one item array).
You need to Deserialize like this:
var Jsonobject = JsonConvert.DeserializeObject<Details>(json);
using classes generated by json2csharp.com:
var Jsonobject = JsonConvert.DeserializeObject<RootObject>(json);
and your classes should be :
public class Datum
{
public string ID { get; set; }
public string Name { get; set; }
}
public class RootObject
{
public List<Datum> data { get; set; }
}
you can always use json2csharp.com to generate right classes for the json.
You can use JavaScriptDeserializer class
string json = #"{""data"":[{""ID"":""1"",""Name"":""ABC""},{""ID"":""2"",""Name"":""DEF""}]}";
Details details = new JavaScriptSerializer().Deserialize<Details>(json);
EDIT: yes, there's nothing wrong with OP's approach, and Servy's answer is correct. You should deserialize not as the List of objects but as the type that contains that List
I have a C# Application in which I am using Json.Net from Nuget.
I get a json from my server which I need to convert into a C# object and with a few modifications I will send it back to the server as json.
Here's my model in C# (which I got after converting the server xsd)
public class Tags
{
public List<Tag> tagData { get; set; }
}
public class Tag
{
public string name {get; set;}
}
Here's my JSON string that is obtained from the server and an attempt at conversion to my model
//Json string obtained from server (hardcoded here for simplicity)
string json = "{tagData: {tags : [ { name : \"John\"}, { name : \"Sherlock\"}]}}";
//An attempt at conversion
var output = JsonConvert.DeserializeObject<Tags>(json);
This is the exception I get with the above code
An unhandled exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll
Additional information: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[jsonnetExample.Tag]' 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 'tagData.tags', line 1, position 17.
After understanding the above message I tried the following 2 things in the hope of fixing it.
A.I tried putting a JsonProperty to my first model.
[JsonProperty(PropertyName = "tags")]
This didn't throw the exception anymore but the output tagData was null.
B. I modified my model as follows
public class Tags
{
public WrapTag tagData { get; set; }
}
public class WrapTag
{
public List<Tag> tags { get; set; }
}
public class Tag
{
public string name {get; set;}
}
This didn't throw any exception and populated the objects as expected. But Now I lost the one to one mapping between xsd(classes from the server) to my client model classes. Is it possible to get this deserialization working without the creation of the WrapTag class?
I would be very glad if someone can point me in the right direction.
Thanks in advance.
Here's one option, using JObject.Parse:
string json = "{tagData: {tags : [ { name : \"John\"}, { name : \"Sherlock\"}]}}";
List<Tag> tagList = JObject.Parse(json)["tagData"]["tags"].ToObject<List<Tag>>();
// or:
// List<Tag> tagList = JObject.Parse(json).SelectToken("tagData.tags")
// .ToObject<List<Tag>>();
Tags tags = new Tags { tagData = tagList };