how to json convert to object and get data loop - asp.net

i have following json.. i was convert my json into objectclass and get subjectid and class id loop through but its not working. i want subjectid and classid please help me how do this.i am new in c# please help me i am very thanful to you guys
[{
"teacherid": 1,
"teachername": "Addi Teacher",
"class": {
"class_id": 2,
"class_name": "Class 9"
},
"subjecname": {
"subject_id": 2,
"Subject_Name": "chemistry"
},
"$$hashKey": "object:10"
}, {
"teacherid": 1,
"teachername": "Addi Teacher",
"class": {
"class_id": 2,
"class_name": "Class 9"
},
"subjecname": {
"subject_id": 4,
"Subject_Name": "Science"
},
"$$hashKey": "object:12"
}, {
"teacherid": 1,
"teachername": "Addi Teacher",
"class": {
"class_id": 2,
"class_name": "Class 9"
},
"subjecname": {
"subject_id": 3,
"Subject_Name": "P.Study"
},
"$$hashKey": "object:14"
}]
//c# class
public class Class
{
public int class_id { get; set; }
public string class_name { get; set; }
}
public class Subjecname
{
public int subject_id { get; set; }
public string Subject_Name { get; set; }
}
public class RootObject
{
public int teacherid { get; set; }
public string teachername { get; set; }
public Class #class { get; set; }
public Subjecname subjecname { get; set; }
public string __invalid_name__$$hashKey { get; set; }
}
// code
subjectobject objsub = new JavaScriptSerializer().Deserialize<subjectobject>(jsonstring);

Do the following steps to achieve what you need:
Use my answer here to generate the C# classes for your JSON. The one you have created manually does not reflect your JSON accurately.
Use NewtonSoft NuGet package to deserialize from json to C# type
Then using Linq or a loop get the properties you need.
Here is what you r code will look like:
var obj = JsonConvert.DeserializeObject<Rootobject>("your json");
var result = obj.Property1.Select(x =>
new { ClassId = x._class.class_id, SubjectId = x.subjecname.subject_id });
By the way, this is what my linked answer will generate for you:
public class Rootobject
{
public Class1[] Property1 { get; set; }
}
public class Class1
{
public int teacherid { get; set; }
public string teachername { get; set; }
public Class2 _class { get; set; }
public Subjecname subjecname { get; set; }
public string hashKey { get; set; }
}
public class Class2
{
public int class_id { get; set; }
public string class_name { get; set; }
}
public class Subjecname
{
public int subject_id { get; set; }
public string Subject_Name { get; set; }
}

Related

concatenate two fields in drop down list

I have a model class
namespace myapp.Models
{
public class SubjectModels
{
[Key]
public int SubjectId { get; set; }
[Required]
public int SubjectType { get; set; }
[Required]
[MinLength(5)]
public string SubjectName { get; set; }
}
}
Here, SubjectType = 1 for Optional and SubjectType = 2 for Compulsory
Now in another class I have to create a drop down for this class,
namespace myapp.Models
{
public class SelectionModels
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int SelectionId { get; set; }
[Required]
[MinLength(5)]
public string SelectionDate { get; set; }
[ForeignKey("SubjectId")]
public SubjectModels Subject { get; set; }
public int SubjectId { get; set; }
}
}
When I genereted controller and create.cshtml via scaffolding, my create controller method:
public ActionResult Create()
{
ViewBag.SubjectId = new SelectList(db.Subjects, "SubjectId", "SubjectName");
return View();
}
But I have to create a drop down concatenating the fields "SubjectName" and "SubjectType". Also, display for SubjectType should be Optional and Compulsory not integer.
for example,
"Optional - ResearchMethodology"
"Compulsory - BioChemistry"
How shall I do this? I googled but could not found suitable solutions. Please help!!!
I would create an extra property in the SubjectModels class.
class SubjectModels
{
public int SubjectId { get; set; }
public int SubjectType { get; set; }
public string SubjectName { get; set; }
public string SubjectNameAndType
{
get
{
return string.Format("{0} - {1}", SubjectName, SubjectType);
}
}
}
Then in the Controller you can use that property to fill the SelectList
var list = new List<SubjectModels>()
{
new SubjectModels()
{
SubjectType = 1,
SubjectName = "Name 1"
},
new SubjectModels()
{
SubjectType = 2,
SubjectName = "Name 2"
}
};
ViewBag.SubjectId = new SelectList(list, "SubjectId", "SubjectNameAndType");
Now you will see the correct values in the DropDownList.
#Html.DropDownListFor(m => m.MyValue, (SelectList)ViewBag.SubjectId, "Select...")

Error converting value JSON to type Entity asp.net

I have to request a JSON like this one:
{
"result": [{
"listEstoqueProduto": [{
"codigoProduto": 0,
"codigoGrupo": 0,
"codigoSubgrupo": 0,
"codigoInternoProduto": 0,
"sequenciaCadastroSubGrupo": 0,
"codigoProdutoCompleto": "string",
"codigoCorProduto": 0,
"descricaoVendasProduto": "string",
"descricaoGrupo": "strimng",
"descricaoSubgrupo": "string",
"descricaoCategoriaProduto": "string",
"descricaoFabricante": "string"
}]
}]
}
But when I try to read return this error: Error converting value myJSONrequest to type ListaProdutos
This is my code:
var requisicaoWeb = WebRequest.CreateHttp("JSONurl");
requisicaoWeb.Method = "GET";
using (var resposta = requisicaoWeb.GetResponse())
{
var streamDados = resposta.GetResponseStream();
StreamReader reader = new StreamReader(streamDados);
object objResponse = reader.ReadToEnd();
Resultado post = JsonConvert.DeserializeObject<Resultado>(objResponse.ToString());
streamDados.Close();
resposta.Close();
}
And those are my entities:
public class Resultado
{
public ListaProdutos[] result { get; set; }
}
public class ListaProdutos
{
public DualProdutos[] listEstoqueProduto { get; set; }
}
public class DualProdutos
{
public int codigoProduto { get; set; }
public int codigoGrupo { get; set; }
public int codigoSubgrupo { get; set; }
public int codigoInternoProduto { get; set; }
public int sequenciaCadastroSubGrupo { get; set; }
public string codigoProdutoCompleto { get; set; }
public int codigoCorProduto { get; set; }
public string descricaoVendasProduto { get; set; }
public string descricaoGrupo { get; set; }
public string descricaoSubgrupo { get; set; }
public string descricaoCategoriaProduto { get; set; }
public string descricaoFabricante { get; set; }
}

JSON.NET error "Cannot deserialize the current JSON array (e.g. [1,2,3]) into type because the type requires a JSON object (e.g. {"name":"value"})"

I have the following WebCleint to call a Restful web service inside my .net console application:-
try
{
using (WebClient wc = new WebClient())
{
wc.Encoding = Encoding.UTF8;
string url = "https://*****/paged?hapikey=*********&properties=website&properties=i_scan&limit=2";//web service url
string tempurl = url.Trim();
var json = wc.DownloadString(tempurl);//get the json
Marketing ipfd = JsonConvert.DeserializeObject<Marketing>(json);//deserialize
}
}
catch (Exception e)
{
//code goes here..
}
where i am using JSON.Net to Deserialize the json object, which will be as follow:-
{
"has-more": true,
"offset": 622438650,
"companies": [
{
"portalId": *******,
"companyId": *****,
"isDeleted": false,
"properties": {
"website": {
"value": "****.net",
"timestamp": 1520938239457,
"source": "CALCULATED",
"sourceId": null,
"versions": [
{
"name": "website",
"value": "*****.net",
"timestamp": 1520938239457,
"source": "CALCULATED",
"sourceVid": [
731938234
]
}
]
}
},
"additionalDomains": [],
"stateChanges": [],
"mergeAudits": []
},
{
"portalId": ******,
"companyId": ******,
"isDeleted": false,
"properties": {
"website": {
"value": "****.***.***",
"timestamp": 1512488590073,
"source": "CALCULATED",
"sourceId": null,
"versions": [
{
"name": "website",
"value": "****.***8.****",
"timestamp": 1512488590073,
"source": "CALCULATED",
"sourceVid": []
}
]
},
"i_scan": {
"value": "Yes",
"timestamp": 1543409493459,
"source": "******",
"sourceId": "**************",
"versions": [
{
"name": "i_scan",
"value": "Yes",
"timestamp": 1543409493459,
"sourceId": *****",
"source": "CRM_UI",
"sourceVid": [],
"requestId": "******"
}
]
}
},
"additionalDomains": [],
"stateChanges": [],
"mergeAudits": []
}
]
}
Here are my classes:-
public class Marketing
{
public Companies companies { get; set; }
}
public class Companies
{
public IList<string> companyId { get; set; }
public IList<Properties> properties { get; set; }
}
public class Properties
{
public IList<Website> website { get; set; }
public IList<I_Scan> i_scan { get; set; }
}
public class Website
{
public string value { get; set; }
}
public class i_Scan
{
public string value { get; set; }
}
but currently i am getting this exception, when i try to de-serialize the JSON object:-
Newtonsoft.Json.JsonSerializationException was caught
HResult=-2146233088
Message=Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'MMarketing.Companies' 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<T> 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 'companies', line 1, position 49.
Source=Newtonsoft.Json
StackTrace:
so i am not sure why JSON.NET is unable to do the Deserialize correctly, as in my case the classes are compatible with the returned json object??
At a first glance it looks like you switched two properties in Making them a List and vice versa.
public class Marketing
{
public List<Companies> companies { get; set; }
}
Is "companies": [ in the json, while "companyId": *****, is the id as a string, not array. Properties is not an array also, but the property versions of properties is.
public class Companies
{
public string companyId { get; set; }
public Properties properties { get; set; }
}
If I'm coming to json blind I like to use http://json2csharp.com/ to generate my class structure for me
public class Version
{
public string name { get; set; }
public string value { get; set; }
public object timestamp { get; set; }
public string source { get; set; }
public List<object> sourceVid { get; set; }
}
public class Website
{
public string value { get; set; }
public object timestamp { get; set; }
public string source { get; set; }
public object sourceId { get; set; }
public List<Version> versions { get; set; }
}
public class Version2
{
public string name { get; set; }
public string value { get; set; }
public long timestamp { get; set; }
public int sourceId { get; set; }
public string source { get; set; }
public List<object> sourceVid { get; set; }
public int requestId { get; set; }
}
public class IScan
{
public string value { get; set; }
public long timestamp { get; set; }
public int source { get; set; }
public int sourceId { get; set; }
public List<Version2> versions { get; set; }
}
public class Properties
{
public Website website { get; set; }
public IScan i_scan { get; set; }
}
public class Company
{
public int portalId { get; set; }
public int companyId { get; set; }
public bool isDeleted { get; set; }
public Properties properties { get; set; }
public List<object> additionalDomains { get; set; }
public List<object> stateChanges { get; set; }
public List<object> mergeAudits { get; set; }
}
public class Marketing
{
public bool has_more { get; set; }
public int offset { get; set; }
public List<Company> companies { get; set; }
}
var result = JsonConvert.DeserializeObject<Marketing>(json);

Deserialized problem GetJsonAsync<T> with Flurl

I want to parse JSON to list with Flurl. My JSON data like this.
{
"api": {
"results": 114,
"fixtures": {
"195": {
"fixture_id": "195",
"event_timestamp": "1543759500",
"event_date": "2018-12-02T14:05:00+00:00",
"league_id": "2",
"round": "Premier League - 14",
"homeTeam_id": "42",
"awayTeam_id": "47",
"homeTeam": "Arsenal",
"awayTeam": "Tottenham",
"status": "Match Finished",
"statusShort": "FT",
"goalsHomeTeam": "4",
"goalsAwayTeam": "2",
"halftime_score": "1 - 2",
"final_score": "4 - 2",
"penalty": null,
"elapsed": "87",
"firstHalfStart": "1543759500",
"secondHalfStart": "1543763100"
}
}}}
and I have also class like this.
class Fixture
{
//public string results { get; set; }
public string fixture_id { get; set; }
public string event_timestamp { get; set; }
public string event_date { get; set; }
public string league_id { get; set; }
public string round { get; set; }
public string homeTeam_id { get; set; }
public string awayTeam_id { get; set; }
public string homeTeam { get; set; }
public string awayTeam { get; set; }
public string status { get; set; }
public string statusShort { get; set; }
public string goalsHomeTeam { get; set; }
public string goalsAwayTeam { get; set; }
public string halftime_score { get; set; }
public string final_score { get; set; }
public string penalty { get; set; }
public string elapsed { get; set; }
public string firstHalfStart { get; set; }
public string secondHalfStart { get; set; }
}
My code is on below
try
{
string _url = string.Format("https://api-football-v1.p.mashape.com/fixtures/date/{0}",(DateTime.Now.Year+"-"+DateTime.Now.Month+"-"+DateTime.Now.Day).ToString());
//PERFORM IN BACKGROUND
await Task.Run(async () =>
{
var fixtures= await _url.WithHeader("Accept", "application/json").WithHeader("X-Mashape-Key", "g5vnMIqeChmshvK6H25VPavNCfhHp1KUtTkjsnOqEM06eP6cOd").GetJsonAsync<Fixture>();
});
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
I try to get JSON data with Flurl.HTTP. But I have deserialized problem. Where is my mistake?
How can I parse this JSON data to IList in c#?
Thank you for your support friends...
You're basically trying to select an inner section of the JSON response, and you can't do that - you need to deserialize to a structure representing the entire response, then traverse this structure to get an individual Fixture. Looking at full response body, you will need to add 2 more classes to contain this structure:
public class ResponseBody
{
public Api api { get; set; }
}
public class Api
{
public int results { get; set; }
public Dictionary<string, Fixture> fixtures { get; set; }
}
Then call GetJsonAsync<ResponseBody>() instead of GetJsonAsync<Fixture>().

Json payload with a toString property

I keep getting a property set to null when I try to deserialize json which contains a toString name for a property
{
"field": "status",
"fieldtype": "jira",
"from": "10000",
"fromString": "Impeded",
"to": "10006",
"toString": "Review"
}
I tried with and without the following JsonProperty
public class ChangelogItem
{
public string field { get; set; }
public string fieldtype { get; set; }
public string from { get; set; }
public string fromString { get; set; }
public string to { get; set; }
//[JsonProperty(PropertyName = "toString")]
//public string newString { get; set; }
public string toString { get; set; }
}
but I keep getting a null value.
Any idea?
The following works fine for me with Json.Net v6.0.3:
public class ChangelogItem
{
public string field { get; set; }
public string fieldtype { get; set; }
public string from { get; set; }
public string fromString { get; set; }
public string to { get; set; }
public string toString { get; set; }
}
Test program:
class Program
{
static void Main(string[] args)
{
string json = #"
{
""field"": ""status"",
""fieldtype"": ""jira"",
""from"": ""10000"",
""fromString"": ""Impeded"",
""to"": ""10006"",
""toString"": ""Review""
}";
ChangelogItem item = JsonConvert.DeserializeObject<ChangelogItem>(json);
Console.WriteLine(item.toString);
}
}
Output:
Review

Resources