Having the following json array:
[{
"Name": "Component1",
"Count": 2,
"Bulletins": [{
"ReferenceNumber": "00000A57",
"Title": "Test test test",
"PublicationDate": "2014-07-02",
"List": ["00000A57"]
},
{
"ReferenceNumber": "10V240000",
"Title": "Bla bla bla",
"PublicationDate": "2010-06-04",
"List": ["10V240000"]
}]
},
{
"Name": "Component2",
"Count": 2,
"Bulletins": [{
"ReferenceNumber": "00-00-0A-57",
"Title": "INFORMATION REGARDING BLA BLA",
"PublicationDate": "2015-05-22",
"List": ["15-00-89-004",
"15-00-89-004A"]
},
{
"ReferenceNumber": "01-02-0B-57",
"Title": "UNSCHEDULED SUPPLEMENTAL SERVICES",
"PublicationDate": "2012-09-28",
"List": ["04-06-01-029",
"04-26-51-029",
"04-26-51-029",
"04-26-51-029",
"04-26-51-029",
"04-26-51-029",
"04-26-51-029"]
}]
}]
I'm using the following code to retrieve the Name and Count values:
public class BulletinsItemsName
{
public string Name { get; set; }
public string Count { get; set; }
public List<BulletinsContainer> blt { get; set; }
}
public class BulletinsContainer
{
public Bulletins Bulletins;
}
public class Bulletins
{
public string ReferenceNumber { get; set; }
public string Title { get; set; }
public string PublicationDate { get; set; }
public string SupersededList { get; set; }
}
To run the request i have:
var req = request.Execute<List<BulletinsItemsName>>(parameters);
And to list values:
foreach(var xx in req.Data)
{
Console.WriteLine(xx.Name);
foreach(var yz in xx.blt) // Object reference not set to an instance of an object
{
Console.WriteLine(yz.Bulletins.Title);
}
}
How can I get values for: ReferenceNumber, Title, PublicationDate and List? All values are correctly returned for Name and Count but when I want to get Bulletins values the following error is thrown: Object reference not set to an instance of an object.
Try using a list of Bulletins instead of BulletinsContainer - It's early morning for me, but I can't see why you need a BulletinsContainer
public List<Bulletins> blt { get; set; }
I would also recommend, if possible, that you name your classes in their singular form.
Related
I have the class below:
public class Product
{
[JsonProperty("image")]
public string ImageURL { get; set; }
[JsonProperty("superDepartment")]
public string SuperDepartment { get; set; }
[JsonProperty("tpnb")]
public long TPNB { get; set; }
[JsonProperty("ContentsMeasureType")]
public string ContentsMeasureType { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("UnitOfSale")]
public int UnitOfSale { get; set; }
[JsonProperty("description")]
public IEnumerator<string> LstDescription { get; set; }
public string Description { get; set; }
[JsonProperty("AverageSellingUnitWeight")]
public decimal AverageSellingUnitWeight { get; set; }
[JsonProperty("UnitQuantity")]
public string UnitQuantity { get; set; }
[JsonProperty("id")]
public long ID { get; set; }
[JsonProperty("ContentsQuantity")]
public int ContentsQuantity { get; set; }
[JsonProperty("department")]
public string Department { get; set; }
[JsonProperty("price")]
public decimal Price { get; set; }
[JsonProperty("unitprice")]
public decimal UnitPrice { get; set; }
}
I have the method on the productController:
public async Task<ActionResult> MakeRequest(string q)// worked
{
var client = new HttpClient();
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "56ac439a92694577a2779f3d0ee0cd85");
var uri = string.Format("https://dev.tescolabs.com/grocery/products/?query={0}&offset={1}&limit={2}", q, 0, 10);
var response = await client.GetAsync(uri);
string body = await response.Content.ReadAsStringAsync();
Product myoutput = JsonConvert.DeserializeObject<Product>(body);
}
return View(body);
}
and I have the model below:
For some reason when I call the method MakeRequest it just shows the information as a string and an error saying Server Error as per picture below we can see the information from the api but it is showing as a string.
error message
The information from the api it should be showing on the table below:
table
How to show the data on the table? Or better how to convert the json array to a net object?
I know there is something missing in the part below of my method:
Product myoutput = JsonConvert.DeserializeObject<Product>(body);
You're passing json string to your View instead of your deserialized Product.
I assume your View expects model of type Product.
The return statement of MakeRequest action should be return View(myOutput);
I'll tell you in a simple way.
Your json model
-uk
--ghs
---products
----results
{
"uk" : {
"ghs" : {
"products": {
"input_query": "babana",
"output_query": "banana",
"filters": {},
"queryPhase": "post_primary",
"totals": {
"all": 109,
"new": 1,
"offer": 47
},
"config": "default",
"results": [
{
"image": "http://img.tesco.com/Groceries/pi/000/0261480000000/IDShot_90x90.jpg",
"superDepartment": "Fresh Food",
"tpnb": 50502269,
"ContentsMeasureType": "KG",
"name": "Tesco Bananas Loose",
"UnitOfSale": 3,
"description": [ "To help ensure the banana farms we source from are best in class we, and our", "suppliers, now work closely with the Rainforest Alliance, an international", "non profit organisation that works to conserve biodiversity and ensure", "sustainable livelihoods worldwide.", "The Rainforest Alliance Certified™ seal on our bananas a green frog nestled", "in a circle – helps us to tell the story of how they are sustainably sourced,", "and assure customers we are sourcing from responsibly managed farms." ],
"AverageSellingUnitWeight": 2.402,
"UnitQuantity": "KG",
"id": 275280804,
"ContentsQuantity": 1,
"department": "Fresh Fruit",
"price": 0.76,
"unitprice": 0.76
},
{
"image": "http://img.tesco.com/Groceries/pi/875/0000010001875/IDShot_90x90.jpg",
"superDepartment": "Fresh Food",
"tpnb": 65728590,
"ContentsMeasureType": "SNGL",
"name": "Tesco Ripe Bananas 5 Pack",
"UnitOfSale": 1,
"AverageSellingUnitWeight": 0.862,
"UnitQuantity": "EACH",
"id": 266419328,
"ContentsQuantity": 5,
"department": "Fresh Fruit",
"price": 0.9,
"unitprice": 0.18
},
{
"image": "http://img.tesco.com/Groceries/pi/416/0000003251416/IDShot_90x90.jpg",
"superDepartment": "Fresh Food",
"tpnb": 77427870,
"ContentsMeasureType": "SNGL",
"name": "Tesco Small Bananas 6 Pack",
"UnitOfSale": 1,
"description": [ "Small Bananas", "Tesco Small Bananas" ],
"AverageSellingUnitWeight": 0.965,
"UnitQuantity": "EACH",
"id": 285157326,
"ContentsQuantity": 6,
"department": "Fresh Fruit",
"price": 0.9,
"unitprice": 0.15
}
],
"suggestions": []
}
}
}
}
If you look at the above json result, you need a more comprehensive model.
For this you can enter the json result into a model here. look here
or keep the result object from its current state with dynamic.
string body = response.Content.ReadAsStringAsync().Result;
dynamic content = JObject.Parse(body);
var products = content.uk.ghs.products.results;
I am trying to deserialise the live chat api json response to access the message id and text by filtering using user_type
JSON response
{{
"events": [
{
"type": "agent_details",
"message_id": 1,
"timestamp": 1532396384,
"user_type": "agent",
"agent": {
"name": "Adam Harris",
"job_title": "Support Agent",
"avatar": "livechat.s3.amazonaws.com/default/avatars/ab5b0666feffd67600206cd519fd77ea.jpg"
}
},
{
"type": "message",
"message_id": 3,
"timestamp": 1532396387,
"user_type": "visitor",
"text": "hi"
}
]
}}
JsonOject Class
class JsonLiveChatEvent
{
public class Rootobject
{
public Event[] events { get; set; }
}
public class Event
{
public string type { get; set; }
public int message_id { get; set; }
public int timestamp { get; set; }
public string user_type { get; set; }
public Agent agent { get; set; }
public string text { get; set; }
}
public class Agent
{
public string name { get; set; }
public string job_title { get; set; }
public string avatar { get; set; }
}
}
JsonConverter
string jsonStr= await Api.Chat.GetPendingMessages(visitorID, licenseID,
var chatEvent = JsonConvert.DeserializeObject<Rootobject>(jsonStr);
The chatEvent object will not let me call chatEvent.events.message_id for example. Any help would be greatly appreciated as this is my first time working with json in c#
There is nothing to do with JSON, you have parsed the JSON data back to Rootobject.
Now you are working with an instance of Rootobject as:
Rootobject chatEvent = JsonConvert.DeserializeObject<Rootobject>(jsonStr);
Event event1 = chatEvent.events[0];
Event event2 = chatEvent.events[1];
Also, consider the answer from Mohammad, because above JSON will throw an exception.
The main problem here is that your json is not valid, there is an extra { in the beginning and an extra } in the end.
Then you could deserialize your json with the types you provided
Your json contains more that one curly brackets so you have to first remove those
so your json look like
{
"events": [
{
"type": "agent_details",
"message_id": 1,
"timestamp": 1532396384,
"user_type": "agent",
"agent": {
"name": "Adam Harris",
"job_title": "Support Agent",
"avatar": "livechat.s3.amazonaws.com/default/avatars/ab5b0666feffd67600206cd519fd77ea.jpg"
}
},
{
"type": "message",
"message_id": 3,
"timestamp": 1532396387,
"user_type": "visitor",
"text": "hi"
}
]
}
After that you have to collect message ids depending upon user_type
So then we create enum for that
public enum UserType
{
agent, visitor
}
then we simply check in events that if user type is matches with any of above enum value.
If your json contains multiple events with multiple user types then collect those into List<int>.
If your json contains only single event of each user type then collect them into string variables.
Rootobject chatEvent = JsonConvert.DeserializeObject<Rootobject>(jsonStr);
List<int> agent_message_ids = new List<int>();
List<int> visitior_message_ids = new List<int>();
//string agent_message_id = string.Empty;
//string visitior_message_id = string.Empty;
foreach (Event e in chatEvent.events)
{
if (e.user_type == UserType.agent.ToString())
{
agent_message_ids.Add(e.message_id);
//agent_message_id = e.message_id;
}
if (e.user_type == UserType.visitor.ToString())
{
visitior_message_ids.Add(e.message_id);
//visitior_message_id = e.message_id;
}
}
We simply take a list of integers that store message ids for particular user_type
Try once may it help you
Result:
agent_message_ids:
visitor_message_ids:
I'm trying to extract data from JSON but i searched and tried many examples but nothing worked for me. I just want messages node and extract its data to datagridview. Json Object looks like:
{
"limit" : "10",
"offset" : "0",
"size" : "10",
"messages": [{
"address": "+12111",
"body": "hello",
"_id": "4113",
"msg_box": "inbox",
"sim_slot": "0"
},
{
"address": "78454",
"body": "my data",
"_id": "4103",
"msg_box": "inbox",
"sim_slot": "0"
},
{
"address": "7421",
"body": "yes",
"_id": "4101",
"msg_box": "outbox",
"sim_slot": "0"
},
{
"address": "+1235454878",
"body": "balance",
"_id": "4099",
"msg_box": "inbox",
"sim_slot": "0"
},
{
"address": "+123545",
"body": "hello",
"_id": "4098",
"msg_box": "inbox",
"sim_slot": "0"
}
]
}
If you have JSON but don't know how to create corresponding classes that deserialize the JSON into objects, json2csharp.com is helpful. You paste in the JSON and it does its best to infer C# classes from it. You might decide to tweak the classes a little as needed but it gives you a good starting point. Given your JSON it outputs this:
public class Message
{
public string address { get; set; }
public string body { get; set; }
public string _id { get; set; }
public string msg_box { get; set; }
public string sim_slot { get; set; }
}
public class RootObject
{
public string limit { get; set; }
public string offset { get; set; }
public string size { get; set; }
public List<Message> messages { get; set; }
}
Now using Newtonsoft.Json you can do this:
var myObject = JsonConvert.DeserializeObject<RootObject>(stringContainingJson);
A property named _id is a little clunky, so you can change the name and use an attribute to map the the property to the JSON element, like this:
[JsonProperty("_id")]
public string Id { get; set; }
Now you can bind the list of Message to your DataGridView.
myDataGridView.DataSource = myObject.messages;
I have a salesforce rest service which returns results in IEnumerable format. Below is a sample results.
[{
"attributes": {
"type": "Account",
"url": "/services/data/v28.0/sobjects/Account/001i0000WK5xYAAT"
},
"RecordType": {
"attributes": {
"type": "RecordType",
"url": "/services/data/v28.0/sobjects/RecordType/012i00000x7FwAAI"
},
"Name": "Health Care Practitioners"
},
"Name": "JOSEPH SANDERS",
"Status_ims__c": "Verified",
},
{
"attributes": {
"type": "Account",
"url": "/services/data/v28.0/sobjects/Account/001i000000WK5xYAAT"
},
"RecordType": {
"attributes": {
"type": "RecordType",
"url": "/services/data/v28.0/sobjects/RecordType/012i0000000x7FwAAI"
},
"Name": "Health Care Practitioners"
},
"Name": "DONALD GRABER",
"Status_ims__c": "Verified",
}]
public class Account
{
public string Name { get{ return GetOption ("Name");} }
public string Status_ims__c { get{ return GetOption ("Status_ims__c");}}
public Attributes attributes {get;}
public RecordType recordType {get;}
}
public class Attributes
{
public string type { get; set; }
public string url { get; set; }
}
public class Attributes2
{
public string type { get; set; }
public string url { get; set; }
}
public class RecordType
{
public Attributes2 attributes { get; set; }
public string Name { get; set; }
}
Above is the structure I have for Account Object. How to convert results to List and map to each property on Account object.
For Example is using json.net ->
var account = JsonConvert.DeserializeObject<List<Account>>(stringData);
Also if there are some differences between the object and the data you can use JsonProperty Annotations
Therefore you could also have more readable properties in your class model like
[JsonProperty("Status_ims__c ")]
public string Status
You can simple use this:
var accounts = JsonConvert.DeserializeObject<List<Account>>("your json string...");
If you use Newtonsoft.Json you can use Newtonsoft.Json.JsonConvert.DeserializeObject method.
Also make sure that your properties have setters in Account class.
Okay first of all, the answer is probably very simple... But after 45 minutes of trying and googling I just can't figure it out!
So I have some problems getting this Json to parse correctly. I created the classes with http://json2csharp.com/ only it doesn't tell me the code to parse it.
My current classes:
public class Representations
{
public string thumb { get; set; }
public string large { get; set; }
public string full { get; set; }
}
public class Search
{
public string id { get; set; }
public string file_name { get; set; }
public Representations representations { get; set; }
}
public class SearchQuery
{
public List<Search> search { get; set; }
public int total { get; set; }
}
JSON:
{
"search": [
{
"id": "0300",
"file_name": "0300.JPG",
"representations": {
"thumb": "thumb.jpg",
"large": "large.jpg",
"full": "0300.jpg"
},
},
{
"id": "0000",
"file_name": "0000.JPG",
"representations": {
"thumb": "thumb.jpg",
"large": "large.jpg",
"full": "0000.jpg"
},
},
{
"id": "0d00",
"file_name": "0d00.JPG",
"representations": {
"thumb": "thumb.jpg",
"large": "large.jpg",
"full": "0d00.jpg"
},
}
],
"total": 3
}
and code:
searchresults = JsonConvert.DeserializeObject<List<SearchQuery>>(JSONCode);
You should deserialize to a SearchQuery, not List<SearchQuery>:
SearchQuery result = JsonConvert.DeserializeObject<SearchQuery>(JSONCode);
and then use the search property to access the list of search results:
List<Search> searchResults = result.search;