Casting Json to Generic List - c#

I have a json file like
var json=[{
"ControlId":2,
"PageNumber":2,
"Top":"11",
"Left":"11",
"Height":50,
"Width":50
}]
and I have a entity class named DocumentControl is like
public class DocumentControlWI
{
public int ControlId { get; set; }
public int PageNumber { get; set; }
public string Top { get; set; }
public string Left { get; set; }
public int Height { get; set; }
public int Width { get; set; }
}
how can I cast the json file to Generic collection of my entity.I am using newtonsoft for desalinizing json. Thanks in advance for help?

Using json.net:
var jsonStr = "[{\"ControlId\":2,\"PageNumber\":2,\"Top\":\"11\",\"Left\":\"11\",\"Height\":50,\"Width\":50}]";
var result = JsonConvert.DeserializeObject<List<DocumentControlWI>>(jsonStr);
1.jsonStr must be a string json.
2.Since you have a json array, you would like to convert it into a collection.

Related

Converting JSON to Object fails - Cannot deserialize the current JSON object into System.Collections.Generic.List

I'm using the API of www.textlocal.in, which returns a JSON formatted object.
JSON
{
"warnings":[
{
"message":"Number is in DND",
"numbers":"917000000000"
}
],
"balance":900,
"batch_id":311110011,
"cost":1,
"num_messages":1,
"message":{
"num_parts":1,
"sender":"TXTLCL",
"content":"Test1"
},
"receipt_url":"",
"custom":"",
"inDND":[
"917000000000"
],
"messages":[
{
"id":"1350123781",
"recipient":918819437284
}
],
"status":"success"
}
My code with which I'm trying to parse the JSON:
private void button1_Click(object sender, EventArgs e)
{
var a = JsonConvert.DeserializeObject<List<jsonToObj[]>>(richTextBox1.Text);
}
public class jsonToObj
{
public warnings[] warnings { get; set; }
public int balance { get; set; }
public int batch_id { get; set; }
public int cost { get; set; }
public int num_messages { get; set; }
public message message { get; set; }
public string receipt_url { get; set; }
public string custom { get; set; }
public messages[] messages { get; set; }
public string status { get; set; }
}
public class warnings
{
public string message { get; set; }
public string numbers { get; set; }
}
public class messages
{
public string id { get; set; }
public int recipient { get; set; }
}
public class message
{
public int num_part { get; set; }
public string sender { get; set; }
public string content { get; set; }
}
I'm getting an exception with the following message:
Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the
current JSON object (e.g. {"name":"value"}) into type
'System.Collections.Generic.List`1[WindowsFormsApp1.Form2+jsonToObj[]]'
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 'warnings', line 1, position
12.'
First of all you have to figure out what your API returns.
Right now you're trying to parse a List of jsonToObj Arrays (List<jsonToObj[]>). You have to decide whether to use a jsonToObj[] or List<jsonToObj> or a simple jsonToObj which your API provides now:
var a = JsonConvert.DeserializeObject<jsonToObj>(richTextBox1.Text);
But this then throws:
JSON integer 918819437284 is too large or small for an Int32. Path 'messages[0].recipient', line 25, position 33."
So make sure you use a Long for that.
public class messages
{
public string id { get; set; }
public long recipient { get; set; }
}
Furthermore you can add inDND to your jsonToObj class if you need the info:
public class jsonToObj
{
...
public string[] inDND { get; set; }
...
}
Based on string you class structure should be like this :
public class Warning
{
public string message { get; set; }
public string numbers { get; set; }
}
public class Message
{
public int num_parts { get; set; }
public string sender { get; set; }
public string content { get; set; }
}
public class Message2
{
public string id { get; set; }
public long recipient { get; set; }
}
public class RootObject
{
public List<Warning> warnings { get; set; }
public int balance { get; set; }
public int batch_id { get; set; }
public int cost { get; set; }
public int num_messages { get; set; }
public Message message { get; set; }
public string receipt_url { get; set; }
public string custom { get; set; }
public List<string> inDND { get; set; }
public List<Message2> messages { get; set; }
public string status { get; set; }
}
It looks like your class structure is not proper, Make use of visual studio and generate C# class from json string and then using that generated class try to deserialize class.
Read : Visual Studio Generate Class From JSON or XML
I simulated your problem and made the following changes that worked:
Change the method that deserializes to this:
var a = JsonConvert.DeserializeObject<jsonToObj>(richTextBox1.Text);
The result of the JSON you receive is not a List, so it will not work to deserialize to List<>.
The recipient property of the messages class receives values larger than an integer, so it must be transformed into a long like this:
public long recipient { get; set; }
These changes solve your problem.
Looks like this is a very old post, still thought of answering.
First of all, your Json data is singular which means, either
var a = JsonConvert.DeserializeObject<List<jsonToObj[]>>(richTextBox1.Text);
or
var a = JsonConvert.DeserializeObject<List<jsonToObj>>(richTextBox1.Text);
may not work for you.
You can either try:
var a = JsonConvert.DeserializeObject<jsonToObj>(richTextBox1.Text);
or
enclose the data with [ and ], which would do the trick.
make sure your parsing single object vs list of objects.

C# - Parsing JSON to multiple objects

I'm trying to create multiple objects out of a JSON result.
My JSON looks like that:
EDIT
[{"quality":"hd","type":"video/mp4","width":1920,"height":1080,"link":"http://player.vimeo.com/external/255898412.hd.mp4?s=8766561d230749d75a0ddde2ddfbeb69e0e5198e&profile_id=175&oauth2_token_id=1040381751","created_time":"2018-02-15T15:46:25+02:00","fps":23.98,"size":3113207678,"md5":"b6beed65b699df870e481045178accc5","link_secure":"https://player.vimeo.com/external/255898412.hd.mp4?s=8766561d230749d75a0ddde2ddfbeb69e0e5198e&profile_id=175&oauth2_token_id=1040381751"},{"quality":"sd","type":"video/mp4","width":640,"height":360,"link":"http://player.vimeo.com/external/255898412.sd.mp4?s=b51b55f6bd6e1af2a8f48571e5804d91e6a82533&profile_id=164&oauth2_token_id=1040381751","created_time":"2018-02-15T15:46:05+02:00","fps":23.98,"size":536864946,"md5":"af227a5526af15d2bce6ac951d6cf06b","link_secure":"https://player.vimeo.com/external/255898412.sd.mp4?s=b51b55f6bd6e1af2a8f48571e5804d91e6a82533&profile_id=164&oauth2_token_id=1040381751"},{"quality":"sd","type":"video/mp4","width":960,"height":540,"link":"http://player.vimeo.com/external/255898412.sd.mp4?s=b51b55f6bd6e1af2a8f48571e5804d91e6a82533&profile_id=165&oauth2_token_id=1040381751","created_time":"2018-02-15T15:46:05+02:00","fps":23.98,"size":1242328160,"md5":"1963f908509b14fd7a40dc46bfa6c519","link_secure":"https://player.vimeo.com/external/255898412.sd.mp4?s=b51b55f6bd6e1af2a8f48571e5804d91e6a82533&profile_id=165&oauth2_token_id=1040381751"},{"quality":"hd","type":"video/mp4","width":1280,"height":720,"link":"http://player.vimeo.com/external/255898412.hd.mp4?s=8766561d230749d75a0ddde2ddfbeb69e0e5198e&profile_id=174&oauth2_token_id=1040381751","created_time":"2018-02-15T15:46:05+02:00","fps":23.98,"size":1977386604,"md5":"af38f067bd39f4f5bb71bad72f925337","link_secure":"https://player.vimeo.com/external/255898412.hd.mp4?s=8766561d230749d75a0ddde2ddfbeb69e0e5198e&profile_id=174&oauth2_token_id=1040381751"},{"quality":"hls","type":"video/mp4","link":"https://player.vimeo.com/external/255898412.m3u8?s=f25b7114977a0c6b37739886da189051ed31999e&oauth2_token_id=1040381751","created_time":"2018-02-15T15:46:25+02:00","fps":23.98,"size":3113207678,"md5":"b6beed65b699df870e481045178accc5","link_secure":"https://player.vimeo.com/external/255898412.m3u8?s=f25b7114977a0c6b37739886da189051ed31999e&oauth2_token_id=1040381751"}]
it should be parsed into 3 objects.
I got a VideoFileModel.cs class that looks like that:
public partial class VideoFileModel
{
[JsonProperty("quality")]
public string Quality { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("width")]
public long? Width { get; set; }
[JsonProperty("height")]
public long? Height { get; set; }
[JsonProperty("link")]
public string Link { get; set; }
[JsonProperty("created_time")]
public System.DateTime CreatedTime { get; set; }
[JsonProperty("fps")]
public double Fps { get; set; }
[JsonProperty("size")]
public long Size { get; set; }
[JsonProperty("md5")]
public string Md5 { get; set; }
[JsonProperty("link_secure")]
public string LinkSecure { get; set; }
}
What I'm trying to do at the moment, is parsing it like that:
string json = Helpers.HTTPFetch(url, method, headers, body, contentType);
var result = JsonConvert.DeserializeObject<VideoFileModel>(json);
but I'm pretty sure it's not working, or at least not in the way I want it to work.
what should I change?
You should simply use List<> when deserializing :
var result = JsonConvert.DeserializeObject<List<VideoFileModel>>(json);
There are is a list of VideoFileModel in your JSON that you trying to deserialize into a single object.
Following gets deserialized:
UPDATE:
As per OP updated JSON. It still gets deserialized:

Deserialize Object into a class does not work

I am trying to set a class for a token using DeserializeObject from the json object i get back from my api. However when i run the below code it sets all the values to null or 0, not the result i am getting from the api.
cs code
var resultString = await result.Content.ReadAsStringAsync();
var post = JsonConvert.DeserializeObject<Token>(resultString);
class
public class Token : ContentPage
{
public int StaffID { get; set; }
public string TokenApi { get; set; }
public string StaffForename { get; set; }
public string StaffSurname { get; set; }
public string StaffEmail { get; set; }
public int PrimaryStaffRoleID { get; set; }
}
JSON response
"{\"code\":201,\"status\":\"Success\",\"message\":\"Object found\",\"data\":{\"StaffID\":14,\"StaffSurname\":\"Test\",\"StaffForename\":\"Test\",\"StaffEmail\":\"test#test.com\",\"PrimaryStaffRoleID\":5,\"TokenApi\":\"testToken\"}}"
Firstly the data which you are trying to map is inside another property in your json called Data and secondly your json does not have a property with name Token
The problem actually is you are not using the correct type that reflects your json, means you don't have correct c# type which would get mapped to json, you can generate correct types using json2charp.com , the correct classes for it are :
public class Data
{
public int StaffID { get; set; }
public string StaffSurname { get; set; }
public string StaffForename { get; set; }
public string StaffEmail { get; set; }
public int PrimaryStaffRoleID { get; set; }
public string TokenApi { get; set; }
}
public class RootObject
{
public int code { get; set; }
public string status { get; set; }
public string message { get; set; }
public Data data { get; set; }
}
Now deserializing using RootObject as type parameter would work perfectly fine like:
var resultString = await result.Content.ReadAsStringAsync();
var post = JsonConvert.DeserializeObject<RootObject>(resultString);
A more good option is to use QuickType.IO which would even generate code for you in c# or any other language that they are supporting.
If you analyze the JSON that you posted, the object that you're trying to Deserialize is inside the "data" property of your json.
I suggest you creating a class to represent the JsonResponse with a Data property. This will be your Token
You are retrieved a string that match this object
public string code {get;set;}
public string Success {get;set;} ...
And Token is matching data in json, so
var post = JsonConvert.DeserializeObject<Token>(resultString.data);
would be better.

How do I deserialize a JSON array using Newtonsoft.Json

[
{
"receiver_tax_id":"1002",
"total":"6949,15",
"receiver_company_name":"Das Company",
"receiver_email":"info#another.com",
"status":0
},
{
"receiver_tax_id":"1001",
"total":"39222,49",
"receiver_company_name":"SAD company",
"receiver_email":"info#mail.com",
"status":1
}
]
Hi, this is my Json data, but I can't deserialize it.
I want to check only "status" value. (first object "status" 0, second object "status" 1).
Example definition:
public class Example
{
[JsonProperty("receiver_tax_id")]
public string receiver_tax_id { get; set; }
[JsonProperty("total")]
public string total { get; set; }
[JsonProperty("receiver_company_name")]
public string receiver_company_name { get; set; }
[JsonProperty("receiver_email")]
public string receiver_email { get; set; }
[JsonProperty("status")]
public int status { get; set; }
}
Deserialization code:
var des = (Example)JsonConvert.DeserializeObject(responseString, typeof(Example));
Console.WriteLine(des.status[0].ToString());
Try this code:
public class Receiver
{
public string receiver_tax_id { get; set;}
public string total { get; set;}
public string receiver_company_name { get; set;}
public int status { get; set;}
}
And deserialize looks like follows:
var result = JsonConvert.DeserializeObject<List<Receiver>>(responseString);
var status = result[0].status;
If you only care about checking status you can use the dynamic type of .NET (https://msdn.microsoft.com/en-us/library/dd264741.aspx)
dynamic deserialized = JObject.Parse(responseString);
int status1 = deserialized[0].status;
int status2 = deserialized[1].status;
//
// do whatever
This way you don't even need the Example class.
From your code and JSON sampels it seems the problem is you're actually deserializing a List<Example> rather than a single Example.
I would do two things:
Make your class follow .NET naming conventions, as you already prefixed them with the proper JsonProperty attributes:
public class Example
{
[JsonProperty("receiver_tax_id")]
public string ReceiverTaxId { get; set; }
[JsonProperty("total")]
public string Total { get; set; }
[JsonProperty("receiver_company_name")]
public string ReceiverCompanyName { get; set; }
[JsonProperty("receiver_email")]
public string ReceiverEmail { get; set; }
[JsonProperty("status")]
public int Status{ get; set; }
}
Deserialize a List<Example> using the generic JsonConvert.DeserializeObject<T> overload instead of the non-generic version you're currently using:
var des = JsonConvert.DeserializeObject<List<Example>>(responseString);
Console.WriteLine(des[0].Status);
You're trying to deserialize an array into an Example object. Try doing it to a List instead:
var des = JsonConvert.DeserializeObject(responseString, typeof(List<Example>)) as List<Example>;

Problems with DeserializeObject with an json array

So I have a problem with DeserializeObject with an json array and I cant find what I am doing wrong here:
{"name":"Pannbiff n\u00f6tf\u00e4rs stekt","number":1128,"nutrientValues":
{"energyKj":694,"energyKcal":166,"protein":17.2,"fat":7.6,"carbohydrates":7}}
My model looks like this:
And my code looks like:
var responseText = streamReader.ReadToEnd();
var jsonSerializer = JsonConvert.DeserializeObject(responseText);
public class Asware
{
public IEnumerable<NutrientValues> nutrientValues { get; set; }
}
public class NutrientValues
{
public int energyKcal { get; set; }
public double protein { get; set; }
public double carbohydrates { get; set; }
public int fat { get; set; }
}
Can't see what can be wrong here I have also tried:
JsonConvert.DeserializeObject>(responseText)
The problem here is that in your source JSON, nutrientValues is a single object, not an array of objects.
If you change your model as follows it should serialise correctly:
public class Asware
{
public NutrientValues nutrientValues { get; set; }
}
Alternatively, if you have control of the JSON, then you can modify it to contain an array of nutrients as follows, the [ ] characters indicate multiple items.
{"name":"Pannbiff n\u00f6tf\u00e4rs stekt","number":1128,"nutrientValues":
[{"energyKj":694,"energyKcal":166,"protein":17.2,"fat":7.6,"carbohydrates":7}]}

Categories

Resources