Convert JSON Result to list<> - c#

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);

Related

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'ModularWebApp.Models.LutUsers[]'

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;}

Parsing JSON With Newtonsoft Throwing Incorrect Format Error

I am attempting to parse my JSON response by taking the response and copy/paste it into Json2CSharp then adding the 2 newly generated classes to the bottom of my current class. (I do not like dealing with multiple classes). The issue that I am having is that when I attempt to access the generated class RootObject I get an error of
An unhandled exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll
Additional information: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Test.RootObject' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
Even though the syntax was converted for me, and I did not change it. What do I need to alter so that this becomes valid workable syntax?
static void Main(string[] args)
{
string userid= "186exa";
var url = "https/?rst=" + userid;
var connectionClient = new WebClient();
connectionClient.Headers.Set("H", "XXXXXXXXXXXX");
connectionClient.Headers.Set("uname", "user");
connectionClient.Headers.Set("pswd", "pwd");
var content = connectionClient.DownloadString(url);
}
EDITThis is the class - will post the JSON shortly
public class List
{
public int id { get; set; }
public string cmu { get; set; }
public int lno { get; set; }
public string clr { get; set; }
public string name { get; set; }
public string origin { get; set; }
public string MajorStyle { get; set; }
public string Style { get; set; }
public string styleImage { get; set; }
public int hid { get; set; }
public string bqty { get; set; }
public int cask { get; set; }
public int local { get; set; }
public string city { get; set; }
}
public class RootObject
{
public string style { get; set; }
public List<List> List { get; set; }
}
This is the retunred JSON
[{"Style":"Cajun","List":[{"id":1225,"cmu":"41.2","lno":10,"name":"Bear","origin":"Lake Sinclair, MO","MajorStyle":"Burn Yo Bottom","Style":"","styleImage":"","hid":1,"bqty":"1.00","cask":0,"local":0,"city":"Amsterdam"}
There are two things at fault with the code you have posted,
The property "clr" does not exist in the JSON.
The JSON ends prematurely, it should have ]}] on the end to be correct.
Fixing both of those issues, the code parses correctly in Newtonsoft when passing it the type RootObject[], as per:
var o = Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject[]>(s);
Where s is the JSON string.
First, you need your classes match with your JSON response, so your classes should look like
public class RootObject
{
public string Style { get; set; }
public List[] List { get; set; }
}
public class List
{
public int id { get; set; }
public string cmu { get; set; }
public int lno { get; set; }
public string clr { get; set; }
public string name { get; set; }
public string origin { get; set; }
public string MajorStyle { get; set; }
public string Style { get; set; }
public string styleImage { get; set; }
public int hid { get; set; }
public string bqty { get; set; }
public int cask { get; set; }
public int local { get; set; }
public string city { get; set; }
}
After that you need to map the response to an object
using Newtonsoft.Json; // Need this to work with JsonConvert
string json = #"[
{
'Style':'Cajun',
'List':
[
{
'id':1225,
'cmu':'41.2',
'lno':10,
'name':'Bear',
'origin':'Lake Sinclair, MO',
'MajorStyle':'Burn Yo Bottom',
'Style':'',
'styleImage':'',
'hid':1,
'bqty':'1.00',
'cask':0,
'local':0,
'city':'Amsterdam'
}
]
}
]";
RootObject[] response = JsonConvert.DeserializeObject<RootObject[]>(json);
Using the keyword List could lead you to mistakes, because there is also a class for C# called List, so be careful.

Linq transformation help needed

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);

How to parse / deserialize JSON returned from rest service in C#

I am getting JSON in string format from a URL whose structure is like this, but I am unable to parse it. It's throwing an exception, any idea how to parse it?
Here is the structure:
{
"pathway":{
"patients":{
"patient":[
{
"patientid":"7703176",
"name":"Abbot, Bud",
"status":"Invited",
"start":"2013-12-07",
"last":"N/A",
"engagement":"N/A",
"drug":"N/A",
"adherence":"N/A",
"vitals":"Current",
"last_appointment":"2013-10-25",
"next_appointment":"None"
},
{
"patientid":"5089554",
"name":"Brennan, Bonnie",
"status":"Connected",
"start":"2013-12-29",
"last":"2014-02-01",
"engagement":"Low",
"drug":" ",
"adherence":" ",
"vitals":"Out of Date",
"last_appointment":"2013-04-21",
"next_appointment":"None"
}
]
}
}
}
i am doing like this:
public class PathWayWrapper
{
public pathway pathway { get; set; }
}
and
public class pathway
{
public List<patient> patients { get; set; }
}
and
public class patient
{
public long patientid { get; set; }
public string name { get; set; }
public string status { get; set; }
public string start { get; set; }
public string last { get; set; }
public string engagement { get; set; }
public string drug { get; set; }
public string adherence { get; set; }
public string vitals { get; set; }
public string last_appointment { get; set; }
public string next_appointment { get; set; }
}
here is my parsing code:
StreamReader reader = new StreamReader(response.GetResponseStream());
string json = reader.ReadToEnd();
var Jsonobject = JsonConvert.DeserializeObject<PathWayWrapper>(json);
objPathway = Jsonobject.pathway;
The classes into which you're deserializing are incorrect. You are missing the "Patients" class.
When I have JSON and am trying to deserialize it I like to use http://json2csharp.com to generate a first cut at the deserialization classes. It's more accurate than trying to do it by hand.
var jsonobject = JsonConvert.DeserializeObject<RootObject>(json);
public class Patient
{
public string patientid { get; set; }
public string name { get; set; }
public string status { get; set; }
public string start { get; set; }
public string last { get; set; }
public string engagement { get; set; }
public string drug { get; set; }
public string adherence { get; set; }
public string vitals { get; set; }
public string last_appointment { get; set; }
public string next_appointment { get; set; }
}
public class Patients
{
public List<Patient> patient { get; set; }
}
public class Pathway
{
public Patients patients { get; set; }
}
public class RootObject
{
public Pathway pathway { get; set; }
}
P.S. The exception you were getting is usually a really good clue that there's something wrong with the way you've defined the deserialization classes.
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[ConsoleApplication1.Program+patient]' 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.

Can't find correct JSON classes

I have next JSON:
[
{
"ApplicationRelations":[
{
"Application":null,
"ApplicationSubcategory":null,
"ApplicationCategory":{
"categoryName":"Default Category",
"id":4
},
"roleOrder":null,
"categoryOrder":null,
"subcategoryOrder":null,
"applicationOrder":null,
"id":6
},
{
"Application":{
"launchUrl":"link",
"trainingUrl":"link",
"installUrl":"link",
"vpn":true,
"overview":"text",
"summary":"text",
"id":12,
"title":"Application"
},
"ApplicationSubcategory":{
"subcategoryName":"Creation",
"id":9
},
"ApplicationCategory":{
"categoryName":"Default Category",
"id":4
},
"roleOrder":15,
"categoryOrder":25,
"subcategoryOrder":35,
"applicationOrder":45,
"id":15
}
],
"roleName":"Role 02",
"roleHeader":"Header of Role 02",
"AnnouncementRelations":[
],
"id":2
}
]
And here are my C# clases:
public class Applications
{
public List<SalesCentralApplicationRelation> salesCentralApplicationRelations { get; set; }
public string RoleName { get; set; }
public string RoleHeader { get; set; }
public List<object> SalesCentralAnnouncementRelations { get; set; }
public int Id { get; set; }
}
public class SalesCentralApplicationRelation
{
public SalesCentralApplication salesCentralApplication { get; set; }
public SalesCentralApplicationSubcategory salesCentralApplicationSubcategory { get; set; }
public SalesCentralApplicationCategory salesCentralApplicationCategory { get; set; }
public int roleOrder { get; set; }
public int categoryOrder { get; set; }
public int subcategoryOrder { get; set; }
public int applicationOrder { get; set; }
public int id { get; set; }
}
public class SalesCentralApplicationCategory
{
public string categoryName { get; set; }
public int id { get; set; }
}
public class SalesCentralApplicationSubcategory
{
public string subcategoryName { get; set; }
public int id { get; set; }
}
public class SalesCentralApplication
{
public string launchUrl { get; set; }
public string trainingUrl { get; set; }
public string installUrl { get; set; }
public bool vpn { get; set; }
public string overview { get; set; }
public string summary { get; set; }
public int id { get; set; }
public string title { get; set; }
}
And my deserialization:
var contents //JSON string above
Applications ApplicationsList = JsonConvert.DeserializeObject<Applications>(contents) as Applications;
And code fails with:
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'App1.MainPage+Applications' 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 '', line 1, position 1.
Checked my classes with json2csharp - all is fine... where is the problem?
Your json is an array, not a single object. Try this:
var ApplicationsList = JsonConvert.DeserializeObject<List<Applications>>(contents);

Categories

Resources