I've got a List of this object:
public class WebinarAttendeesList {
public int wa_id { get; set; }
public int PID { get; set; }
public string FullName { get; set; }
public string Email { get; set; }
public string JoinTime { get; set; }
public string TimeInSession { get; set; }
public string LeaveTime { get; set; }
public int FirstPollCount { get; set; }
public int SecondPollCount { get; set; }
public int AttendedWebinar { get; set; }
public int Makeup { get; set; }
public string Comments { get; set; }
public string RegistrantKey { get; set; }
public string webinarKey { get; set; }
}
I'm using this Linq code:
var webinars = new
{
Webinars = r.GroupBy(x => new { x.PID, x.FullName }).
Select(y => new
{
PID = y.Key.PID,
FullName = y.Key.FullName,
AffReceived = 0,
Attendances = y.Select(z => new
{
WebinarKey = z.webinarKey,
RegistrantKey = z.RegistrantKey,
TimeInSession = z.TimeInSession,
FirstPollCount = z.FirstPollCount,
SecondPollCount = z.SecondPollCount,
AttendedWebinar = z.AttendedWebinar
})
})
};
string json = JsonConvert.SerializeObject(webinars);
to transform the List to JSON. But, I think I'd rather
have it transformed into a List<FinalWebinarAttendeesList> (see below
definition). The JSON that it produces looks correct and passes lint.
When I try to do this:
List<FinalWebinarAttendeesList> fl = JsonConvert.DeserializeObject<List<FinalWebinarAttendeesList>>(json);
I get an error:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type
'System.Collections.Generic.List`1[WebinarProject.Models.FinalWebinarAttendeesList]'
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
'Webinars', line 1, position 12.
How can I either transform this directly into the object I want, or be able to deserialize it into the object I want?
FinalWebinarAttendeesList definition:
public class FinalWebinarAttendeesList
{
public FinalWebinar Webinars {get; set; }
}
public class FinalWebinar
{
public int PtID { get; set; }
public string FullName { get; set; }
public int AffReceived { get; set; }
public List<FinalWebinarAttendee> Attendances { get; set; }
}
public class FinalWebinarAttendee
{
public string RegistrantKey { get; set; }
public string TimeInSession { get; set; }
public int FirstPollCount { get; set; }
public int SecondPollCount { get; set; }
public int AttendedWebinar { get; set; }
}
I created a json sample output using random data and and I found that you are trying to deserialize the json with the wrong object.
Json output:
{"Webinars":[{"PID":453,"FullName":"jdis","Attendances":[{"WebinarKey":"kdnsaod","RegistrantKey":"udhaso","TimeInSession":"hdija","FirstPollCount":45,"SecondPollCount":45,"AttendedWebinar":0}]}]}
The object has de following structure:
public class Attendance
{
public string WebinarKey { get; set; }
public string RegistrantKey { get; set; }
public string TimeInSession { get; set; }
public int FirstPollCount { get; set; }
public int SecondPollCount { get; set; }
public int AttendedWebinar { get; set; }
}
public class Webinar
{
public int PID { get; set; }
public string FullName { get; set; }
public List<Attendance> Attendances { get; set; }
}
public class RootObject
{
public List<Webinar> Webinars { get; set; }
}
And for Deserializing the object:
var result = JsonConvert.DeserializeObject<RootObject>(json);
You created only one Webinar instance, but you are trying to deserialize a list of Webinars. Try:
FinalWebinarAttendeesList fl = JsonConvert.DeserializeObject<FinalWebinarAttendeesList>(json);
Related
i have this code , and i'm trying to retrive json data from a c# web api, when ever i try to deserialize the json i'm getting : Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'ModularWebApp.Models.LutUsers[]' 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 'content', line 1, position 11.'
i tried a lot of other ways to do and it still not working , any help?
here is my model
[JsonProperty("matricule_agent")]
public string matricule_agent {get; set;}
[JsonProperty("grade_agent")]
public string grade_agent { get; set; }
[JsonProperty("nom_utils")]
public string nom_utils { get; set; }
[JsonProperty("prenom_utils")]
public string prenom_utils { get; set; }
and Here is my controller
public ActionResult LutUser()
{
ViewBag.Message = "Your LookUp Table Page.";
List<LutUsers> lutUsers = new List<LutUsers>();
LutUsers[] Users = new LutUsers[0];
HttpResponseMessage response = client.GetAsync(client.BaseAddress +
"/user/findusers").Result;
//Checking the response is successful or not which is sent using HttpClient
if (response.IsSuccessStatusCode)
{
//Storing the response details recieved from web api
Response.Write("<script>alert('Connection Made successfully!');</script>");
JavaScriptSerializer js = new JavaScriptSerializer();
// Person[] persons = js.Deserialize<Person[]>(json);
string data = response.Content.ReadAsStringAsync().Result;
lutUsers = JsonConvert.DeserializeObject<List<LutUsers>>(data);
// lutUsers = JsonConvert.DeserializeObject<List<LutUsers>>(data);
Response.Write(Users);
} else
{
Response.Write("<script>alert('Connection not made!');</script>");
}
//returning the employee list to view
return View(lutUsers);
}
If this is what your data looks like,
{
"content": [
{
"id_utilisateurs": 1,
"matricule_agent": "BE4",
"nom_utils": "laguerre",
"prenom_utils": "Vellie",
"sexe_utils": "F",
"dat2naiss_utils": "15-12-2020",
"grade_agent": "Agent 4",
"email_utils": "Laguerre.vellie#gmail.com",
"mot2pass_utils": null,
"typ_compte": "agent",
"is_active_utils": 1,
"date_enreg_utils": "05-05-2021 15:55:00",
"affectation": "villate",
"is_first_login": 1,
"mot2pass_utils_defaut": null
}
],
"status": "success"
}
then you need to have the rootObject that has content as a list/array of objects (Content).
public class Rootobject
{
[JsonObject("content")]
public List<Content> Content { get; set; }
[JsonObject("status")]
public string Status { get; set; }
}
public class Content
{
public int id_utilisateurs { get; set; }
public string matricule_agent { get; set; }
public string nom_utils { get; set; }
public string prenom_utils { get; set; }
public string sexe_utils { get; set; }
public string dat2naiss_utils { get; set; }
public string grade_agent { get; set; }
public string email_utils { get; set; }
public object mot2pass_utils { get; set; }
public string typ_compte { get; set; }
public int is_active_utils { get; set; }
public string date_enreg_utils { get; set; }
public string affectation { get; set; }
public int is_first_login { get; set; }
public object mot2pass_utils_defaut { get; set; }
}
Remember, your data is an object that contains content and status as the keys. content's value is an array.. so, deserialize it like this,
var rootObject = JsonConvert.DeserializeObject<Rootobject>(data)
List<Content> lutUsers = rootObject.Content;
Create class
public class ResultData
{
public int id_utilisateurs { get; set; }
public string matricule_agent { get; set; }
public string nom_utils { get; set; }
public string prenom_utils { get; set; }
public string sexe_utils { get; set; }
public DateTime dat2naiss_utils { get; set; }
public string grade_agent { get; set; }
public string email_utils { get; set; }
public string mot2pass_utils { get; set; }
public string typ_compte { get; set; }
public int is_active_utils { get; set; }
public DateTime date_enreg_utils { get; set; }
public string affectation { get; set; }
public int is_first_login { get; set; }
public string mot2pass_utils_defaut { get; set; }
}
and replace
lutUsers = JsonConvert.DeserializeObject<List<LutUsers>>(data);
with
var resultData = JsonConvert.DeserializeObject<List<ResultData>>(data);
It looks like the data you care about is buried in the content array.
Wrap your LutUsers class in a container class with the following properties:
public List<LutUsers> content {get; set;}
public string status {get;set;}
ERROR
Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the
current JSON object (e.g. {"name":"value"}) into type
'System.Collections.Generic.List`1[RechargePortal.Models.ProviderOperator]'
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 'providers', line 1, position
13.'
List<ProviderOperator> GetProvideOperator(string service)
{
string json = new System.Net.WebClient().DownloadString("URL");
List<ProviderOperator> ob = new List<ProviderOperator>();
ob = JsonConvert.DeserializeObject<List<ProviderOperator>>(json);
ob = ob.Where(x => x.Service.Equals(service)).ToList();
return ob;
}
JSON RESULT
{
"providers":[
{
"provider_id":0,
"provider_name":"PAY2ALL",
"provider_code":"PAY2ALL",
"service_id":10,
"service":"Pay2All Cash",
"provider_image":"",
"status":"Success"
},
{
"provider_id":1,
"provider_name":"AIRTEL",
"provider_code":"A",
"service_id":1,
"service":"Recharge",
"provider_image":"provider_icons\/airtel.png",
"status":"Success"
},
{
"provider_id":2,
"provider_name":"VODAFONE",
"provider_code":"V",
"service_id":1,
"service":"Recharge",
"provider_image":"provider_icons\/vodafone.png",
"status":"Success"
}
]
}
Model
public class ProviderOperator
{
public string Provider_id { get; set; }
public string Provider_name { get; set; }
public string Provider_code { get; set; }
public string Service { get; set; }
public string Provider_image { get; set; }
public string Status { get; set; }
}
You should try following class:
public class ProviderOperator
{
public List<Provider> providers { get; set; }
}
public class Provider
{
public int provider_id { get; set; }
public string provider_name { get; set; }
public string provider_code { get; set; }
public int service_id { get; set; }
public string service { get; set; }
public string provider_image { get; set; }
public string status { get; set; }
}
var ob = JsonConvert.DeserializeObject<ProviderOperator>(json);
Output:
Your Json Result is in different format and the class structure you are using
to parse json is in different format.
You need to create two separate classes as follows
Class Structure
public class ProviderOperator
{
public List<ProviderInfo> providers { get; set; }
}
public class ProviderInfo
{
public int provider_id { get; set; }
public string provider_name { get; set; }
public string provider_code { get; set; }
public int service_id { get; set; }
public string service { get; set; }
public string provider_image { get; set; }
public string status { get; set; }
}
Parsing Response
var result = JsonConvert.DeserializeObject<ProvderOperator>(json);
This is my code:
dynamic resultObject = JsonConvert.DeserializeObject(Result);
string final = JsonConvert.SerializeObject(resultObject);
This my the result of final (JSON):
How do get the selling_price field? like doing final.selling_price?
My class:
public class ItemPriceJson {
public string item_price_id { get; set; }
public string item_code { get; set; }
public string item_desc { get; set; }
public string trnx_unit { get; set; }
public string price_level_id { get; set; }
public string price_level_code { get; set; }
public string selling_price { get; set; }
} // itemPriceJson
You're not deserializing the json to a dynamic object properly. First of all, it's an array, not an object.
So, try it like this:
dynamic resultObject = JArray.Parse(Result); //Dynamic object.
var sellingPrice = resultObject[0].selling_price; //Get the selling price. Could also use some casting here.
You should change your class to
public class ItemPriceJson {
public int item_price_id { get; set; }
public string item_code { get; set; }
public string item_desc { get; set; }
public string trnx_unit { get; set; }
public int price_level_id { get; set; }
public string price_level_code { get; set; }
public int selling_price { get; set; }
} // itemPriceJson
and deserialize it with
var results = JsonConvert.DeserializeObject<List<ItemPriceJson>>( Result );
because the json result contains an array of objects and so you need a collection for deserialization
Create a POCO class which describes the object for example;
public class MyItemObject
{
public string item_price_id { get; set; }
public string item_desc { get; set; }
public string trnx_unit { get; set; }
}
Then use JsonConvert to deserialize a instance of the object.
var result = JsonConvert.DeserializeObject<MyItemObject>(json);
EDIT
As json is a list/collection deserialize as a list type;
var listResult = JsonConvert.DeserializeObject<List<MyItemObject>>(json);
public class ItemPriceJson {
public string item_price_id { get; set; }
public string item_code { get; set; }
public string item_desc { get; set; }
public string trnx_unit { get; set; }
public string price_level_id { get; set; }
public string price_level_code { get; set; }
public string selling_price { get; set; }
}
And you can use the Newtonsoft json library
var result = JsonConvert.DeserializeObject<List<ItemPriceJson>>(jsonstring);
I have this JSON file which i want to Deserialize.
{
"agencies":[
{
"id":44,
"name":"National Aeronautics and Space Administration",
"countryCode":"USA",
"abbrev":"NASA",
"type":1,"infoURL":"http:\/\/www.nasa.gov",
"wikiURL":"http:\/\/en.wikipedia.org\/wiki\/National_Aeronautics_and_Space_Administration",
"infoURLs":[
"http:\/\/www.nasa.gov"
]
}
],
"total":0,
"count":1,
"offset":0
}
I currenly have this code for getting the JSON and trying to deserialize it.
RestClient client = new RestClient("https://launchlibrary.net/1.2/agency");
RestRequest request = new RestRequest("NASA",Method.GET);
var results = client.Execute(request).Content;
MessageBox.Show(JsonConvert.DeserializeObject(results).ToString());
// Deserialize
RootObject rootObject = JsonConvert.DeserializeObject<RootObject>(results);
MessageBox.Show(rootObject.agencies.Count.ToString());
And this
public class Agency
{
public int id { get; set; }
public string name { get; set; }
public string countryCode { get; set; }
public string abbrev { get; set; }
public int type { get; set; }
public string infoURL { get; set; }
public string wikiURL { get; set; }
public List<string> infoURLs { get; set; }
}
public class RootObject
{
public List<Agency> agencies { get; set; }
public int total { get; set; }
public int count { get; set; }
public int offset { get; set; }
}
I can easily get to the things just inside the object such as total and count but not the array agencies.
How do I do this?
I'm only interested in the data inside the agencies array and not the total, count and offset
I've create a class for deserialize this JSON
public class Self
{
public string href { get; set; }
}
public class Team
{
public string href { get; set; }
}
public class Links
{
public Self _self { get; set; }
public Team team { get; set; }
}
public class Player
{
public int id { get; set; }
public string name { get; set; }
public string position { get; set; }
public int jerseyNumber { get; set; }
public string dateOfBirth { get; set; }
public string nationality { get; set; }
public string contractUntil { get; set; }
public string marketValue { get; set; }
}
public class RootObject
{
public Links _links { get; set; }
public int count { get; set; }
public List<Player> players { get; set; }
}
public struct Player_Struct
{
public string id;
public string name;
public string position;
public int jerseyNumber;
public string dateOfBirth;
public string nationality;
public string contractUntil;
public string marketValue;
}
So I made a function to create an HttpRequest and the relative object:
string requestUrl = teams.link_teams;
string responseText = parser.Request(requestUrl);
var obj = JsonConvert.DeserializeObject<Players.RootObject>(responseText);
Now the problem's that the compiler return this exception:
Unhandled exception 'Newtonsoft.Json.JsonSerializationException' in Newtonsoft.Json.dll
Ulteriori informazioni: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'SF_DebugProject.API.Players+Links' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path '_links', line 1, position 11.
So with the fix hint I've tried to repair the error change the object into:
List<Players.RootObject> obj = JsonConvert.DeserializeObject<List<Players.RootObject>>(responseText);
but in this way I can't see any attribute of the rootobject when I do the foreach. What I doing wrong?
From what I understand you want to deserialize a JSON string in a RootObject that contains a list of players.
The classes should look like this:
public class Rootobject
{
public _Links _links { get; set; }
public int count { get; set; }
public Player[] players { get; set; }
}
public class _Links
{
public _Self _self { get; set; }
public Team team { get; set; }
}
public class _Self
{
public string href { get; set; }
}
public class Team
{
public string href { get; set; }
}
public class Player
{
public int id { get; set; }
public string name { get; set; }
public string position { get; set; }
public int jerseyNumber { get; set; }
public string dateOfBirth { get; set; }
public string nationality { get; set; }
public string contractUntil { get; set; }
public string marketValue { get; set; }
}
So what you should do is something like the following :
var obj = JsonConvert.DeserializeObject<RootObject>(response);
foreach(var player in obj.players)
{
// some stuff
}