I want to deserialize JSON response received by Telegram Bot API by getUpdate() method.
JSON data:
{
"ok": true,
"result": [
{
"update_id": 920493886,
"message": {
"message_id": 123,
"from": {
"id": 219633031,
"first_name": "Shreeeeeee",
"username": "Winner7777"
},
"chat": {
"id": 219633031,
"first_name": "Shreeeeeee",
"username": "Winner7777",
"type": "private"
},
"date": 1472457375,
"text": "Aata aala"
}
},
{
"update_id": 920493887,
"message": {
"message_id": 124,
"from": {
"id": 219633031,
"first_name": "Shreeeeeee",
"username": "Winner7777"
},
"chat": {
"id": 219633031,
"first_name": "Shreeeeeee",
"username": "Winner7777",
"type": "private"
},
"date": 1472457387,
"text": "Jeva tuzyakadun reply aala tevha"
}
},
{
"update_id": 920493888,
"message": {
"message_id": 125,
"from": {
"id": 219633031,
"first_name": "Shreeeeeee",
"username": "Winner7777"
},
"chat": {
"id": 219633031,
"first_name": "Shreeeeeee",
"username": "Winner7777",
"type": "private"
},
"date": 1472457443,
"text": "Deposite"
}
},
{
"update_id": 920493889,
"message": {
"message_id": 127,
"from": {
"id": 201520743,
"first_name": "Chandrakant",
"last_name": "Kumathekar",
"username": "chandrakant_k"
},
"chat": {
"id": 201520743,
"first_name": "Chandrakant",
"last_name": "Kumathekar",
"username": "chandrakant_k",
"type": "private"
},
"date": 1472457645,
"text": "\/menu",
"entities": [
{
"type": "bot_command",
"offset": 0,
"length": 5
}
]
}
},
{
"update_id": 920493890,
"message": {
"message_id": 128,
"from": {
"id": 219633031,
"first_name": "Shreeeeeee",
"username": "Winner7777"
},
"chat": {
"id": 219633031,
"first_name": "Shreeeeeee",
"username": "Winner7777",
"type": "private"
},
"date": 1472457670,
"text": "\/menu",
"entities": [
{
"type": "bot_command",
"offset": 0,
"length": 5
}
]
}
},
{
"update_id": 920493891,
"message": {
"message_id": 130,
"from": {
"id": 201520743,
"first_name": "Chandrakant",
"last_name": "Kumathekar",
"username": "chandrakant_k"
},
"chat": {
"id": 201520743,
"first_name": "Chandrakant",
"last_name": "Kumathekar",
"username": "chandrakant_k",
"type": "private"
},
"date": 1472457848,
"text": "Deposite"
}
},
{
"update_id": 920493892,
"message": {
"message_id": 132,
"from": {
"id": 201520743,
"first_name": "Chandrakant",
"last_name": "Kumathekar",
"username": "chandrakant_k"
},
"chat": {
"id": 201520743,
"first_name": "Chandrakant",
"last_name": "Kumathekar",
"username": "chandrakant_k",
"type": "private"
},
"date": 1472457883,
"text": "Deposite"
}
},
{
"update_id": 920493893,
"message": {
"message_id": 133,
"from": {
"id": 219633031,
"first_name": "Shreeeeeee",
"username": "Winner7777"
},
"chat": {
"id": 219633031,
"first_name": "Shreeeeeee",
"username": "Winner7777",
"type": "private"
},
"date": 1472468407,
"text": "\/menu",
"entities": [
{
"type": "bot_command",
"offset": 0,
"length": 5
}
]
}
},
{
"update_id": 920493894,
"message": {
"message_id": 134,
"from": {
"id": 219633031,
"first_name": "Shreeeeeee",
"username": "Winner7777"
},
"chat": {
"id": 219633031,
"first_name": "Shreeeeeee",
"username": "Winner7777",
"type": "private"
},
"date": 1472473070,
"text": "\/menu",
"entities": [
{
"type": "bot_command",
"offset": 0,
"length": 5
}
]
}
}
]
}
I have generated classes from json2csharp
public class From
{
public int id { get; set; }
public string first_name { get; set; }
public string last_name { get; set; }
public string username { get; set; }
}
public class Chat
{
public int id { get; set; }
public string first_name { get; set; }
public string last_name { get; set; }
public string type { get; set; }
public string username { get; set; }
}
public class Entity
{
public string type { get; set; }
public int offset { get; set; }
public int length { get; set; }
}
public class Message
{
public int message_id { get; set; }
public From from { get; set; }
public Chat chat { get; set; }
public int date { get; set; }
public string text { get; set; }
public List<Entity> entities { get; set; }
}
public class Result
{
public int update_id { get; set; }
public Message message { get; set; }
}
public class RootObject
{
public bool ok { get; set; }
public List<Result> result { get; set; }
}
using newtonsoft to deserialization
var d = Newtonsoft.Json.JsonConvert.DeserializeObject(rcvd_data);
what to do next? how to put this all at work? I am confused please help.
To deserialization use this code:
RootObject ro = JsonConvert.DeserializeObject<RootObject>(rcvd_data);
And in ro you have all data.
EXAMPLE
bool ok = ro.ok;
foreach(Result r in ro.result)
{
int uId = r.update_id;
Message m = r.message;
int msgId = m.message_id;
}
string data = #"{""ok"":true,""result"":[{""update_id"":920493886,...";
RootObject ro = Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject>(data);
foreach (Result result in ro.result)
{
//two example fields
Console.WriteLine("update_id= " + result.update_id);
Console.WriteLine("message text= "+result.message.text);
}
Based on: https://yts.am/api/v2/list_movies.json (Source: https://yts.am/api)
I used: http://json2csharp.com/ to create classes
Copy and paste the result of the get request of postman to json2csharp to automatically create the classes that you need
And once created, i used them on a Service like this:
private string URL = "https://yts.am/api/v2/list_movies.json";
public async Task<List<Movie>> GetMovies()
{
var httpClient = new HttpClient();
var json = await httpClient.GetStringAsync(URL);
RootObject lista = Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject>(json);
List<Movie> todoes = lista.data.movies;
return todoes;
}
I'm using Newtonsoft.Json
Try this way
var d = Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject>(rcvd_data);
then d will contain list of RootObject. By iterating using foreach you can get all the properties of RootObject model
Related
I am writing a tool to work with resume.json files (project) and am creating a Json Schema to validate user input. I'm trying to automate this with Json.Net.Schema but the output always makes all properties required, regardless of whether the properties have the [Required] or [JsonRequired] attributes.
Schema Generation Code
var generator = new JSchemaGenerator
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
SchemaIdGenerationHandling = SchemaIdGenerationHandling.TypeName
};
var schema = generator.Generate(typeof(Resume));
var sb = new StringBuilder();
schema.WriteTo(new JsonTextWriter(
new IndentedTextWriter(
new StringWriter(sb),
" ")
)
{
Formatting = Formatting.Indented,
IndentChar = ' ', Indentation = 2,
QuoteName = true
}, new JSchemaWriterSettings
{
Version = SchemaVersion.Draft7
});
File.WriteAllText("E:\\resume.schema", sb.ToString());
Resume Class (and children)
public class Resume
{
[Required]
public Basics Basics { get; set; }
public Work[] Work { get; set; }
public Volunteer[] Volunteer { get; set; }
public Education[] Education { get; set; }
public Award[] Awards { get; set; }
public Publication[] Publications { get; set; }
public Skill[] Skills { get; set; }
public Language[] Languages { get; set; }
public Interest[] Interests { get; set; }
public Reference[] References { get; set; }
}
public class Award
{
[Required]
public string Title { get; set; }
public string Date { get; set; }
public string Awarder { get; set; }
public string Summary { get; set; }
}
public class Basics
{
[Required]
public string Name { get; set; }
public string Label { get; set; }
public Uri Picture { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string Website { get; set; }
public string Summary { get; set; }
public Location Location { get; set; }
public Profile[] Profiles { get; set; }
}
public class Education
{
[Required]
public string Institution { get; set; }
public string Area { get; set; }
public string StudyType { get; set; }
public string StartDate { get; set; }
public string EndDate { get; set; }
public string Gpa { get; set; }
public string[] Courses { get; set; }
}
public class Interest
{
[Required]
public string Name { get; set; }
public string[] Keywords { get; set; }
}
public class Language
{
[Required]
public string language { get; set; }
[Required]
public string Fluency { get; set; }
}
public class Location
{
public string Address { get; set; }
[Required]
public string PostalCode { get; set; }
[Required]
public string City { get; set; }
[Required]
public string CountryCode { get; set; }
public string Region { get; set; }
}
public class Profile
{
[Required]
public string Network { get; set; }
[Required]
public string Username { get; set; }
[Required]
public string Url { get; set; }
}
public class Publication
{
[Required]
public string Name { get; set; }
public string Publisher { get; set; }
public string ReleaseDate { get; set; }
public string Website { get; set; }
public string Summary { get; set; }
}
public class Reference
{
[Required]
public string Name { get; set; }
public string reference { get; set; }
}
public class Skill
{
[Required]
public string Name { get; set; }
[Required]
public string Level { get; set; }
public string[] Keywords { get; set; }
}
public class Volunteer
{
[Required]
public string Organization { get; set; }
[Required]
public string Position { get; set; }
public string Website { get; set; }
public string StartDate { get; set; }
public string EndDate { get; set; }
public string Summary { get; set; }
public string[] Highlights { get; set; }
}
public class Work
{
[Required]
public string Company { get; set; }
[Required]
public string Position { get; set; }
public string Website { get; set; }
[Required]
public string StartDate { get; set; }
public string EndDate { get; set; }
public string Summary { get; set; }
public string[] Highlights { get; set; }
}
Current Output
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "Resume",
"definitions": {
"Award": {
"$id": "Award",
"type": [
"object",
"null"
],
"properties": {
"title": {
"type": "string"
},
"date": {
"type": [
"string",
"null"
]
},
"awarder": {
"type": [
"string",
"null"
]
},
"summary": {
"type": [
"string",
"null"
]
}
},
"required": [
"title",
"date",
"awarder",
"summary"
]
},
"Basics": {
"$id": "Basics",
"type": "object",
"properties": {
"name": {
"type": "string"
},
"label": {
"type": [
"string",
"null"
]
},
"picture": {
"type": [
"string",
"null"
],
"format": "uri"
},
"email": {
"type": [
"string",
"null"
]
},
"phone": {
"type": [
"string",
"null"
]
},
"website": {
"type": [
"string",
"null"
]
},
"summary": {
"type": [
"string",
"null"
]
},
"location": {
"$id": "Location",
"type": [
"object",
"null"
],
"properties": {
"address": {
"type": [
"string",
"null"
]
},
"postalCode": {
"type": "string"
},
"city": {
"type": "string"
},
"countryCode": {
"type": "string"
},
"region": {
"type": [
"string",
"null"
]
}
},
"required": [
"address",
"postalCode",
"city",
"countryCode",
"region"
]
},
"profiles": {
"$id": "Profile[]",
"type": [
"array",
"null"
],
"items": {
"$id": "Profile",
"type": [
"object",
"null"
],
"properties": {
"network": {
"type": "string"
},
"username": {
"type": "string"
},
"url": {
"type": "string"
}
},
"required": [
"network",
"username",
"url"
]
}
}
},
"required": [
"name",
"label",
"picture",
"email",
"phone",
"website",
"summary",
"location",
"profiles"
]
},
"Education": {
"$id": "Education",
"type": [
"object",
"null"
],
"properties": {
"institution": {
"type": "string"
},
"area": {
"type": [
"string",
"null"
]
},
"studyType": {
"type": [
"string",
"null"
]
},
"startDate": {
"type": [
"string",
"null"
]
},
"endDate": {
"type": [
"string",
"null"
]
},
"gpa": {
"type": [
"string",
"null"
]
},
"courses": {
"$id": "String[]",
"type": [
"array",
"null"
],
"items": {
"type": [
"string",
"null"
]
}
}
},
"required": [
"institution",
"area",
"studyType",
"startDate",
"endDate",
"gpa",
"courses"
]
},
"Interest": {
"$id": "Interest",
"type": [
"object",
"null"
],
"properties": {
"name": {
"type": "string"
},
"keywords": {
"$id": "String[]",
"type": [
"array",
"null"
],
"items": {
"type": [
"string",
"null"
]
}
}
},
"required": [
"name",
"keywords"
]
},
"Language": {
"$id": "Language",
"type": [
"object",
"null"
],
"properties": {
"language": {
"type": "string"
},
"fluency": {
"type": "string"
}
},
"required": [
"language",
"fluency"
]
},
"Location": {
"$ref": "Location"
},
"Profile": {
"$ref": "Profile"
},
"Publication": {
"$id": "Publication",
"type": [
"object",
"null"
],
"properties": {
"name": {
"type": "string"
},
"publisher": {
"type": [
"string",
"null"
]
},
"releaseDate": {
"type": [
"string",
"null"
]
},
"website": {
"type": [
"string",
"null"
]
},
"summary": {
"type": [
"string",
"null"
]
}
},
"required": [
"name",
"publisher",
"releaseDate",
"website",
"summary"
]
},
"Reference": {
"$id": "Reference",
"type": [
"object",
"null"
],
"properties": {
"name": {
"type": "string"
},
"reference": {
"type": [
"string",
"null"
]
}
},
"required": [
"name",
"reference"
]
},
"Skill": {
"$id": "Skill",
"type": [
"object",
"null"
],
"properties": {
"name": {
"type": "string"
},
"level": {
"type": "string"
},
"keywords": {
"$id": "String[]",
"type": [
"array",
"null"
],
"items": {
"type": [
"string",
"null"
]
}
}
},
"required": [
"name",
"level",
"keywords"
]
},
"Volunteer": {
"$id": "Volunteer",
"type": [
"object",
"null"
],
"properties": {
"organization": {
"type": "string"
},
"position": {
"type": "string"
},
"website": {
"type": [
"string",
"null"
]
},
"startDate": {
"type": [
"string",
"null"
]
},
"endDate": {
"type": [
"string",
"null"
]
},
"summary": {
"type": [
"string",
"null"
]
},
"highlights": {
"$id": "String[]",
"type": [
"array",
"null"
],
"items": {
"type": [
"string",
"null"
]
}
}
},
"required": [
"organization",
"position",
"website",
"startDate",
"endDate",
"summary",
"highlights"
]
},
"Work": {
"$id": "Work",
"type": [
"object",
"null"
],
"properties": {
"company": {
"type": "string"
},
"position": {
"type": "string"
},
"website": {
"type": [
"string",
"null"
]
},
"startDate": {
"type": "string"
},
"endDate": {
"type": [
"string",
"null"
]
},
"summary": {
"type": [
"string",
"null"
]
},
"highlights": {
"$id": "String[]",
"type": [
"array",
"null"
],
"items": {
"type": [
"string",
"null"
]
}
}
},
"required": [
"company",
"position",
"website",
"startDate",
"endDate",
"summary",
"highlights"
]
}
},
"type": "object",
"properties": {
"basics": {
"$ref": "Basics"
},
"work": {
"$id": "Work[]",
"type": [
"array",
"null"
],
"items": {
"$ref": "Work"
}
},
"volunteer": {
"$id": "Volunteer[]",
"type": [
"array",
"null"
],
"items": {
"$ref": "Volunteer"
}
},
"education": {
"$id": "Education[]",
"type": [
"array",
"null"
],
"items": {
"$ref": "Education"
}
},
"awards": {
"$id": "Award[]",
"type": [
"array",
"null"
],
"items": {
"$ref": "Award"
}
},
"publications": {
"$id": "Publication[]",
"type": [
"array",
"null"
],
"items": {
"$ref": "Publication"
}
},
"skills": {
"$id": "Skill[]",
"type": [
"array",
"null"
],
"items": {
"$ref": "Skill"
}
},
"languages": {
"$id": "Language[]",
"type": [
"array",
"null"
],
"items": {
"$ref": "Language"
}
},
"interests": {
"$id": "Interest[]",
"type": [
"array",
"null"
],
"items": {
"$ref": "Interest"
}
},
"references": {
"$id": "Reference[]",
"type": [
"array",
"null"
],
"items": {
"$ref": "Reference"
}
}
},
"required": [
"basics",
"work",
"volunteer",
"education",
"awards",
"publications",
"skills",
"languages",
"interests",
"references"
]
}
How do I get the schema generator to honor the Required attributes?
JSchemaGenerator has a property DefaultRequired:
Gets or sets the default required state of schemas.
For some reason, the default value for this property is Required.AllowNull, as shown in the source:
public JSchemaGenerator()
{
_schemaReferenceHandling = SchemaReferenceHandling.Objects;
_defaultRequired = Required.AllowNull;
}
If you change it to Required.Default, only those properties explicitly marked as required, e.g. with [Required] or [JsonProperty(Required = Required.Always)], will be listed as required in the schema:
var generator = new JSchemaGenerator
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
SchemaIdGenerationHandling = SchemaIdGenerationHandling.TypeName,
DefaultRequired = Required.Default,
};
The default value for DefaultRequired isn't documented, but probably should be. You might open an issue with Newtonsoft requesting a clarification to the documentation.
Demo fiddle here.
So I am trying to return a couple of ListItems from a sharepoint list. I get the content back just fine, but when it Deserializes the content, the calculated column returns a null value. I just do not get it since the value is there in the content.
string geturl = "https://graph.microsoft.com/v1.0/sites/XXXXX.sharepoint.com,495435b4-60c3-49b7-8f6e-1d262a120ae5,0fad9f67-35a8-4c0b-892e-113084058c0a/lists/18a725ac-83ef-48fb-a5cb-950ca2378fd0/items/9?expand=fields(select=SerialNumber,id)";
public async Task<string> GetDataWithTokenAsync(string url, string token, string listitem)
{
var httpClient = new System.Net.Http.HttpClient();
System.Net.Http.HttpResponseMessage response;
try
{
var request = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, url);
//Add the token in Authorization header
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
response = await httpClient.SendAsync(request);
var content = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<SharePointListItems.RootObject>(content);
if (listitem == "id")
{
return result.fields.Id;
}
else
{
return result.fields.SerialNumber;
}
}
catch (Exception ex)
{
return ex.ToString();
}
}
Here is the class (shortened):
public class SharePointListItems
{
public class Fields
{
[JsonProperty("#odata.etag")]
public string ODataETag { get; set; }
//General Parameters
...
public string SerialNumber { get; set; } // Calculated field in Sharepoint
public string Id { get; set; }
...
}
public class RootObject
{
[JsonProperty("#odata.context")]
public string ODataContext { get; set; }
[JsonProperty("#odata.etag")]
public string ODataETag { get; set; }
[JsonProperty("fields#odata.context")]
public string FieldsODataContext { get; set; }
public Fields fields { get; set; }
}
}
The content that is returned with my GET is:
"{\"#odata.context\":\"https://graph.microsoft.com/v1.0/$metadata#sites('XXXXX.sharepoint.com%2C495435b4-60c3-49b7-8f6e-1d262a120ae5%2C0fad9f67-35a8-4c0b-892e-113084058c0a')/lists('18a725ac-83ef-48fb-a5cb-950ca2378fd0')/items/$entity\",\"#odata.etag\":\"\\\"a69b1840-239d-42ed-9b20-8789761fb06a,3\\\"\",\"createdDateTime\":\"2018-08-25T22:44:16Z\",\"eTag\":\"\\\"a69b1840-239d-42ed-9b20-8789761fb06a,3\\\"\",\"id\":\"9\",\"lastModifiedDateTime\":\"2018-08-25T22:44:16Z\",\"webUrl\":\"https://XXXXX.sharepoint.com/sites/GeneratorApp/Lists/GenApp/9_.000\",\"createdBy\":{\"user\":{\"email\":\"XXXXX#XXXXX.com\",\"id\":\"b0465821-e891-4f44-9e18-27e875f1b75d\",\"displayName\":\"XXXXX\"}},\"lastModifiedBy\":{\"user\":{\"email\":\"XXXXX#XXXXX.com\",\"id\":\"b0465821-e891-4f44-9e18-27e875f1b75d\",\"displayName\":\"XXXXX\"}},\"parentReference\":{},\"contentType\":{\"id\":\"0x0100E19591A4ECA81542AEA41A6AAFED6781\"},\"fields#odata.context\":\"https://graph.microsoft.com/v1.0/$metadata#sites('XXXXX.sharepoint.com%2C495435b4-60c3-49b7-8f6e-1d262a120ae5%2C0fad9f67-35a8-4c0b-892e-113084058c0a')/lists('18a725ac-83ef-48fb-a5cb-950ca2378fd0')/items('9')/fields/$entity\",\"fields\":{\"#odata.etag\":\"\\\"a69b1840-239d-42ed-9b20-8789761fb06a,3\\\"\",\"SerialNumber\":\"20180824-1353-DC6-Generator-A\",\"id\":\"9\"}}"
If I add a line
Jobject json = Jobject.Parse(content);
I get the following response (changed endpoint to get multiple ListItems):
{{
"#odata.context": "https://graph.microsoft.com/v1.0/$metadata#sites('XXXXX.sharepoint.com%2C495435b4-60c3-49b7-8f6e-1d262a120ae5%2C0fad9f67-35a8-4c0b-892e-113084058c0a')/lists('18a725ac-83ef-48fb-a5cb-950ca2378fd0')/items",
"value": [
{
"#odata.etag": "\"a69b1840-239d-42ed-9b20-8789761fb06a,3\"",
"createdDateTime": "2018-08-25T22:44:16Z",
"eTag": "\"a69b1840-239d-42ed-9b20-8789761fb06a,3\"",
"id": "9",
"lastModifiedDateTime": "2018-08-25T22:44:16Z",
"webUrl": "https://XXXXX.sharepoint.com/sites/GeneratorApp/Lists/GenApp/9_.000",
"createdBy": {
"user": {
"email": "XXXXX#XXXXX.com",
"id": "b0465821-e891-4f44-9e18-27e875f1b75d",
"displayName": "XXXXX"
}
},
"lastModifiedBy": {
"user": {
"email": "XXXXX#XXXXX.com",
"id": "b0465821-e891-4f44-9e18-27e875f1b75d",
"displayName": "XXXXX"
}
},
"parentReference": {},
"contentType": {
"id": "0x0100E19591A4ECA81542AEA41A6AAFED6781"
},
"fields#odata.context": "https://graph.microsoft.com/v1.0/$metadata#sites('XXXXX.sharepoint.com%2C495435b4-60c3-49b7-8f6e-1d262a120ae5%2C0fad9f67-35a8-4c0b-892e-113084058c0a')/lists('18a725ac-83ef-48fb-a5cb-950ca2378fd0')/items('9')/fields/$entity",
"fields": {
"#odata.etag": "\"a69b1840-239d-42ed-9b20-8789761fb06a,3\"",
"SerialNumber": "20180824-1353-DC6-Generator-A",
"id": "9"
}
},
{
"#odata.etag": "\"13f60f9e-1bf2-4803-93b9-c45234963d47,3\"",
"createdDateTime": "2018-08-25T22:45:55Z",
"eTag": "\"13f60f9e-1bf2-4803-93b9-c45234963d47,3\"",
"id": "10",
"lastModifiedDateTime": "2018-08-25T22:45:55Z",
"webUrl": "https://XXXXX.sharepoint.com/sites/GeneratorApp/Lists/GenApp/10_.000",
"createdBy": {
"user": {
"email": "XXXXX#XXXXX.com",
"id": "b0465821-e891-4f44-9e18-27e875f1b75d",
"displayName": "XXXXX"
}
},
"lastModifiedBy": {
"user": {
"email": "XXXXX#XXXXX.com",
"id": "b0465821-e891-4f44-9e18-27e875f1b75d",
"displayName": "XXXXX"
}
},
"parentReference": {},
"contentType": {
"id": "0x0100E19591A4ECA81542AEA41A6AAFED6781"
},
"fields#odata.context": "https://graph.microsoft.com/v1.0/$metadata#sites('XXXXX.sharepoint.com%2C495435b4-60c3-49b7-8f6e-1d262a120ae5%2C0fad9f67-35a8-4c0b-892e-113084058c0a')/lists('18a725ac-83ef-48fb-a5cb-950ca2378fd0')/items('10')/fields/$entity",
"fields": {
"#odata.etag": "\"13f60f9e-1bf2-4803-93b9-c45234963d47,3\"",
"SerialNumber": "20180824-1416-DC6-Generator-B",
"id": "10"
}
},
{
"#odata.etag": "\"00024848-0d4e-4ee8-b018-f1653af2a577,3\"",
"createdDateTime": "2018-08-25T22:47:30Z",
"eTag": "\"00024848-0d4e-4ee8-b018-f1653af2a577,3\"",
"id": "11",
"lastModifiedDateTime": "2018-08-25T22:47:30Z",
"webUrl": "https://XXXXX.sharepoint.com/sites/GeneratorApp/Lists/GenApp/11_.000",
"createdBy": {
"user": {
"email": "XXXXX#XXXXX.com",
"id": "b0465821-e891-4f44-9e18-27e875f1b75d",
"displayName": "XXXXX"
}
},
"lastModifiedBy": {
"user": {
"email": "XXXXX#XXXXX.com",
"id": "b0465821-e891-4f44-9e18-27e875f1b75d",
"displayName": "XXXXX"
}
},
"parentReference": {},
"contentType": {
"id": "0x0100E19591A4ECA81542AEA41A6AAFED6781"
},
"fields#odata.context": "https://graph.microsoft.com/v1.0/$metadata#sites('XXXXX.sharepoint.com%2C495435b4-60c3-49b7-8f6e-1d262a120ae5%2C0fad9f67-35a8-4c0b-892e-113084058c0a')/lists('18a725ac-83ef-48fb-a5cb-950ca2378fd0')/items('11')/fields/$entity",
"fields": {
"#odata.etag": "\"00024848-0d4e-4ee8-b018-f1653af2a577,3\"",
"SerialNumber": "20180824-1438-DC6-Generator-R",
"id": "11"
}
},
{
"#odata.etag": "\"7c8e80ed-6fea-408a-9594-2b7b13e3691b,3\"",
"createdDateTime": "2018-08-25T23:02:43Z",
"eTag": "\"7c8e80ed-6fea-408a-9594-2b7b13e3691b,3\"",
"id": "12",
"lastModifiedDateTime": "2018-08-25T23:02:43Z",
"webUrl": "https://XXXXX.sharepoint.com/sites/GeneratorApp/Lists/GenApp/12_.000",
"createdBy": {
"user": {
"email": "XXXXX#XXXXX.com",
"id": "b0465821-e891-4f44-9e18-27e875f1b75d",
"displayName": "XXXXX"
}
},
"lastModifiedBy": {
"user": {
"email": "XXXXX#XXXXX.com",
"id": "b0465821-e891-4f44-9e18-27e875f1b75d",
"displayName": "XXXXX"
}
},
"parentReference": {},
"contentType": {
"id": "0x0100E19591A4ECA81542AEA41A6AAFED6781"
},
"fields#odata.context": "https://graph.microsoft.com/v1.0/$metadata#sites('XXXXX.sharepoint.com%2C495435b4-60c3-49b7-8f6e-1d262a120ae5%2C0fad9f67-35a8-4c0b-892e-113084058c0a')/lists('18a725ac-83ef-48fb-a5cb-950ca2378fd0')/items('12')/fields/$entity",
"fields": {
"#odata.etag": "\"7c8e80ed-6fea-408a-9594-2b7b13e3691b,3\"",
"SerialNumber": "20180824-1456-DC6-Generator-C",
"id": "12"
}
}
]
}}
It just seems like I am going round in circles now.
What I want to end up is with a List of id & SerialNumber.
[Code updated to reflect my comment]
Since I really answered the question of the topic the 2nd thing I was asking was a totally separate issue.
So what happened was that I was looking at the wrong data. There happened to also be an 'id' field also in the area I was looking at, so it was showing that 'id' and not the one I was really looking for. When I setup the appropriate entry point, I was able to work down to the appropriate field.
I am calling a REST service to get back a JSON structure.
The error I get is
Test method BarPanda.Web.Services.Test.PosServiceTests.GetMenu threw exception:
System.MissingMethodException: No parameterless constructor defined for this object.
The original JSON is as follows (partial)
{
"count": 3,
"limit": 50,
"_links": {
"self": {
"etag": "b49a27c7e7c663af8d6a736e24fac7f5",
"href": "https://api.omnivore.io/0.1/locations/gcBdM7TL/menu/categories/" ,
"profile": "https://panel.omnivore.io/docs/api#category_list"
}
},
"_embedded": {
"categories": [
{
"id": "AdiRjiAp",
"name": "Drinks",
"_links": {
"items": {
"etag": "05dad4d734401321a4854cf4f0369102",
"href": "https://api.omnivore.io/0.1/locations/gcBdM7TL/menu/categories/AdiRjiAp/items/" ,
"profile": "https://panel.omnivore.io/docs/api#menu-item_list"
},
"self": {
"etag": "05dad4d734401321a4854cf4f0369102",
"href": "https://api.omnivore.io/0.1/locations/gcBdM7TL/menu/categories/AdiRjiAp/" ,
"profile": "https://panel.omnivore.io/docs/api#category_retrieve"
}
},
"_embedded": {
"items": [
{
"id": "gki84ia9",
"in_stock": true,
"modifier_groups_count": 0,
"name": "Soda",
"open": false,
"pos_id": "gki84ia9",
"price": 150,
"price_levels": [
{
"id": "Byineidy",
"price": 150
},
{
"id": "g4T4dTBj",
"price": 200
},
{
"id": "K6czkc8b",
"price": 250
}
],
"_links": {
"modifier_groups": {
"href": "https://api.omnivore.io/0.1/locations/gcBdM7TL/menu/items/gki84ia9/modifier_groups/" ,
"profile": "https://panel.omnivore.io/docs/api#modifier-group_list"
},
"self": {
"etag": "c59b380aed5c1f33915b028b739df955",
"href": "https://api.omnivore.io/0.1/locations/gcBdM7TL/menu/items/gki84ia9/" ,
"profile": "https://panel.omnivore.io/docs/api#menu-item_retrieve"
}
}
},
{
"id": "doTaLTyg",
"in_stock": true,
"modifier_groups_count": 0,
"name": "Orange Juice",
"open": false,
"pos_id": "doTaLTyg",
"price": 175,
"price_levels": [
{
"id": "L4iqKid8",
"price": 175
},
{
"id": "K6T8MTzb",
"price": 300
}
],
"_links": {
"modifier_groups": {
"href": "https://api.omnivore.io/0.1/locations/gcBdM7TL/menu/items/doTaLTyg/modifier_groups/" ,
"profile": "https://panel.omnivore.io/docs/api#modifier-group_list"
},
"self": {
"etag": "d3ae9754edb321f18e192ebea446baeb",
"href": "https://api.omnivore.io/0.1/locations/gcBdM7TL/menu/items/doTaLTyg/" ,
"profile": "https://panel.omnivore.io/docs/api#menu-item_retrieve"
}
}
}
]
}
},
I am trying to deserialize it with the following code and object classes
var response = _client.Execute(request);
var converter = new JsonDeserializer();
var menu = converter.Deserialize<PosMenu>(response);
PosMenu
[DataContract]
public class PosMenu
{
[DataMember]
public int VenueId { get; set; }
[DataMember]
public int count { get; set; }
[DataMember]
public PosMenuEmbedded _embedded { get; set; }
}
PosMenuEmbedded
[DataContract]
public class PosMenuEmbedded
{
[DataMember]
public long UniqueId { get; set; }
[DataMember]
public PosMenuCategory[] categories { get; set; }
[DataMember]
public int PosMenuId { get; set; }
}
PosMenuCategory
[DataContract]
public class PosMenuCategory
{
}
Note: I have taken all properties out of this class for now just to see if I could get it working with a blank class, but alas not.
If I comment out the line in PosMenuEmbedded
public PosMenuCategory[] categories { get; set; }
It succeeds. If I put it back in, it fails, even with an empty class.
Can anyone suggest why this might be?
[DataMember]
public List<PosMenuCategory> categories { get; set; }
im facing a problem with probably selfreference Looping:
Model:
public class ProtectedAccount
{
public int Id { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime Created { get; private set; }
public DateTime? Changed { get; set; }
public bool Disabled { get; set; }
public virtual ICollection<ProtectedAccountMember> Members { get; set; }
public virtual ProtectedAccountType Type { get; set; }
}
public class ProtectedAccountMember
{
public int Id { get; set; }
[StringLength(300)]
public string Name { get; set; }
[Index]
public virtual ProtectedAccount ProtectedAccount { get; set; }
}
Controller:
[ResponseType(typeof(ProtectedAccount))]
[Route("ProtectedAccounts/{id}/Members")]
[HttpGet]
public IHttpActionResult GetProtectedAccountMembers(int id)
{
var protectedAccount = db.ProtectedAccounts.Find(id);
if (protectedAccount == null)
{
return NotFound();
}
return Ok(protectedAccount.Members.ToList());
}
the data wich i receive for an GET seems to Loop recursive through all navigations:
[
{
"ProtectedAccount": {
"Members": [
{
"Id": 2,
"Name": "XXX, XX",
},
{
"Id": 3,
"Name": "XX, XX",
}
],
"Type": null,
"Id": 25,
"ObjectGUID": "76bf65e7-af60-4fe8-b3e1-90afbfd65b65",
"Name": "XXX",
},
"Id": 1,
"Name": "test",
},
{
"ProtectedAccount": {
"Members": [
{
"Id": 1,
"Name": "test",
},
{
"Id": 3,
"Name": "XX, XX",
"SamAccountName": "XX",
"Disabled": false
}
],
"Type": null,
"Id": 25,
"ObjectGUID": "76bf65e7-af60-4fe8-b3e1-90afbfd65b65",
"Name": "XXXX",
},
"Id": 2,
"Name": "XX, XX",
},
{
"ProtectedAccount": {a
"Members": [
{
"Id": 1,
"Name": "test",
"SamAccountName": "XXX",
"Disabled": false
},
{
"Id": 2,
"Name": "XX, XX",
"SamAccountName": "XX",
"Disabled": false
}
],
"Type": null,
"Id": 25,
"ObjectGUID": "76bf65e7-af60-4fe8-b3e1-90afbfd65b65",
"Name": "XXX",
},
"Id": 3,
"Name": "XX, XX",
}
]
There is only one "ProtectedAccount" in the database. DO i have to use DTO to overcome this issue? I tried some configuration via the json formatsettings but didnt get any better results.
From your code, you are only returing the protectedAccount.Members, hence you could do a projection query as below
var results = ctx.ProtectedAccountMembers
.Where(member => member.ProtectedAccount.Id == protectedAccount.Id)
.Select(member => new { member.Id, member.Name }).ToList();
I need get data from this JSON file, but I'm not able to get the data using C# and Newtonsoft. Can anyone help me to solve this issue? The data is from the Thomson Reuters API. I've tried other articles, but it's always a failure.
JSON:
{
"RequestKey": {
"NameType": "RIC",
"Service": "IDN",
"Name": "AEDMYR=R"
},
"QoS": {
"TimelinessInfo": {
"TimeInfo": 0,
"Timeliness": "REALTIME"
},
"RateInfo": {
"TimeInfo": 0,
"Rate": "TICK_BY_TICK"
}
},
"Status": {
"StatusMsg": "OK",
"StatusCode": 0
},
"Fields": {
"Field": [
{
"Name": "HIGH_1",
"DataType": "Double",
"Double": 117.3428
},
{
"Name": "LOW_1",
"DataType": "Double",
"Double": 117.0143
},
{
"Name": "YRHIGH",
"DataType": "Double",
"Double": 121.8861
},
{
"Name": "YRLOW",
"DataType": "Double",
"Double": 95.205
},
{
"Name": "HIGH_TIME",
"DataType": "Utf8String",
"Utf8String": "03:33"
},
{
"Name": "LOW_TIME",
"DataType": "Utf8String",
"Utf8String": "02:55"
},
{
"Name": "BKGD_REF",
"DataType": "Utf8String",
"Utf8String": "UAEDir/MalayRgt"
},
{
"Name": "GEN_TEXT16",
"DataType": "Utf8String",
"Utf8String": "AED vs MYR"
},
{
"Name": "GV2_TEXT",
"DataType": "Utf8String",
"Utf8String": "AEDMYR"
},
{
"Name": "VALUE_TS1",
"DataType": "Utf8String",
"Utf8String": "08:48:00"
},
{
"Name": "VALUE_TS2",
"DataType": "Utf8String",
"Utf8String": "08:47:01"
},
{
"Name": "VALUE_TS3",
"DataType": "Utf8String",
"Utf8String": "08:46:01"
},
{
"Name": "MONTH_HIGH",
"DataType": "Double",
"Double": 118.0954
},
{
"Name": "MONTH_LOW",
"DataType": "Double",
"Double": 114.0702
},
{
"Name": "WEEK_HIGH",
"DataType": "Double",
"Double": 117.3428
},
{
"Name": "WEEK_LOW",
"DataType": "Double",
"Double": 116.8654
},
{
"Name": "SCALING",
"DataType": "Utf8String",
"Utf8String": "100"
},
{
"Name": "CF_ASK",
"DataType": "Double",
"Double": 117.4272
},
{
"Name": "CF_BID",
"DataType": "Double",
"Double": 117.2443
},
{
"Name": "CF_CLOSE",
"DataType": "Double",
"Double": 116.7792
},
{
"Name": "CF_DATE",
"DataType": "Utf8String",
"Utf8String": "23 DEC 2015"
},
{
"Name": "CF_HIGH",
"DataType": "Double",
"Double": 117.3428
},
{
"Name": "CF_LAST",
"DataType": "Double",
"Double": 117.2443
},
{
"Name": "CF_LOW",
"DataType": "Double",
"Double": 117.0143
},
{
"Name": "CF_NETCHNG",
"DataType": "Double",
"Double": 0.4651
},
{
"Name": "CF_OPEN",
"DataType": "Double",
"Double": 116.7792
},
{
"Name": "CF_SOURCE",
"DataType": "Utf8String",
"Utf8String": "ThomRtrs"
},
{
"Name": "CF_TICK",
"DataType": "Utf8String",
"Utf8String": "⇧"
},
{
"Name": "CF_TIME",
"DataType": "Utf8String",
"Utf8String": "08:48:00"
},
{
"Name": "CF_NAME",
"DataType": "Utf8String",
"Utf8String": "UAEDir/MalayRgt"
},
{
"Name": "BQOS",
"DataType": "Utf8String",
"Utf8String": "0"
},
{
"Name": "PQOS",
"DataType": "Utf8String",
"Utf8String": "RT"
},
{
"Name": "ConcreteService",
"DataType": "Utf8String",
"Utf8String": "IDN_FD3"
},
{
"Name": "MSG_TYPE",
"DataType": "Int32",
"Int32": 0
},
{
"Name": "REC_STATUS",
"DataType": "Int32",
"Int32": 0
}
]
}
}
Deserialization code:
var result = "";
using (var objStreamReader = new StreamReader("RetrieveItem_Response_2.json"))
{
result = objStreamReader.ReadToEnd();
}
JObject joResponse = JObject.Parse(result);
JArray joArray = (JArray)(joResponse["RetrieveItem_Response_2"]["ItemResponse"]);
List<Rootobject> objRootobject = JsonConvert.DeserializeObject<List<Rootobject>>(joArray.ToString());
C# Classes:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public class Rootobject
{
public Requestkey RequestKey { get; set; }
public Qos QoS { get; set; }
public Status Status { get; set; }
public Fields Fields { get; set; }
}
public class Requestkey
{
public string NameType { get; set; }
public string Service { get; set; }
public string Name { get; set; }
}
public class Qos
{
public Timelinessinfo TimelinessInfo { get; set; }
public Rateinfo RateInfo { get; set; }
}
public class Timelinessinfo
{
public int TimeInfo { get; set; }
public string Timeliness { get; set; }
}
public class Rateinfo
{
public int TimeInfo { get; set; }
public string Rate { get; set; }
}
public class Status
{
public string StatusMsg { get; set; }
public int StatusCode { get; set; }
}
public class Fields
{
public Field[] Field { get; set; }
}
public class Field
{
public string Name { get; set; }
public string DataType { get; set; }
public float Double { get; set; }
public string Utf8String { get; set; }
public int Int32 { get; set; }
}
It looks like you have all of your classes defined correctly. To deserialize the JSON you just need to do this:
Rootobject obj = JsonConvert.DeserializeObject<Rootobject>(result);
You can dump out the field values like this:
foreach (Field f in obj.Fields.Field)
{
string value;
switch (f.DataType)
{
case "Utf8String": value = f.Utf8String; break;
case "Double": value = f.Double.ToString(); break;
case "Int32": value = f.Int32.ToString(); break;
default: value = "(unknown)"; break;
}
Console.WriteLine(f.Name + ": " + value);
}
Fiddle: https://dotnetfiddle.net/JD3jPD