Can I deserialize a JSON object by object in C#? - c#

I have a big json file. It consist of information of different articles posted on internet. I'm wandering if it's possible to deserialize it object by object. For example, to make a loop and with every iteration a single object from json to be deserialized, then the next one, and so on.
Here are just only two of json file's objects (there are some thousands out there)
[
{
"source": "unimedia",
"title": "some title",
"original_time": "ora: 20:03, 06 dec 2006",
"datetime": "2006-12-06T20:03:00+00:00",
"views": 398,
"comments": 1,
"content": " some content",
"id": "13",
"url": "http://unimedia.info/stiri/-13.html"
},
{
"source": "unimedia",
"title": "some another title",
"original_time": "ora: 20:13, 06 dec 2006",
"datetime": "2006-12-06T20:13:00+00:00",
"views": 173,
"comments": 1,
"content": "some another content",
"id": "19",
"url": "http://unimedia.info/stiri/-19.html"
},
...
]
Here is my class:
class jsonData
{
public string source { get; set; }
public string title { get; set; }
public string original_time { get; set; }
public string datetime { get; set; }
public int views { get; set; }
public int comments { get; set; }
public string content { get; set; }
public int id { get; set; }
public string url { get; set; }
}
Can anybody help me with that ?

You just need to use use Newtonsoft.Json
Newtonsoft Json
string json = File.ReadAllText(PathFile);
jsonData obj = JsonConvert.DeserializeObject<jsonData>(json);

Related

C# Json.net Unexpected character encountered while parsing value: [

public class JSON_Browse_Root
{
public string browse_content { get; set; }
public List<JSON_Browse_Content> Content { get; set; }
}
public class JSON_Browse_Content
{
public string link { get; set; }
public string image { get; set; }
public string title { get; set; }
public string description { get; set; }
public string rating { get; set; }
public string genre { get; set; }
}
using (var client = new HttpClient())
{
using (HttpResponseMessage response = await client.GetAsync("https://myjsonurl.com"))
using (HttpContent responseData = response.Content)
{
var jsonData = await responseData.ReadAsStringAsync();
var root = JsonConvert.DeserializeObject<JSON_Browse_Root>(jsonData);
}
}
JSON:
{
"browse_content": [
{
"link": "https:\/\/blah",
"image": "https:\/\/blahblah.blah.gif",
"title": "Mr. Southern Hospitality",
"description": "He got old money",
"rating": "e",
"author": "",
"genre": "Comedy - Original"
},
{
"link": "https:\/\/blah",
"image": "https:\/\/blahblah.blah.png",
"title": "Throwverwatch",
"description": "Based on the competitive overwatch experience",
"rating": "t",
"author": "",
"genre": "Comedy - Parody"
}
An exception of type 'Newtonsoft.Json.JsonReaderException' occurred in
System.Private.CoreLib.ni.dll but was not handled in user code
Unexpected character encountered while parsing value: [
I used this JSON for iOS and Android apps and it's worked perfectly. Also, jsonlint.com says the JSON is valid. Not sure why it's erroring out on the [ character.
Assuming your JSON is missing the ending due to a copy/paste error, the actual problem you have is that your model class is wrong. You have a string property called browse_content and the deserialiser is trying to feed the array (i.e. the [...]) part of the JSON into it, hence you get the error about the unexpected character [. So the simple fix is to update your model to this:
public class JSON_Browse_Root
{
public List<JSON_Browse_Content> browse_content { get; set; }
}

extract data from JSON to datagridview winforms c#

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;

JSON Parse Bank Holiday Calendar

I have a ASP MVC project that is accessing an API to get bank holiday dates: https://www.gov.uk/bank-holidays.json
When I parse the JSON however I am getting problems when I try to get down to the level of the 'events'. Currently I have:
var json = new WebClient().DownloadString("https://www.gov.uk/bank-holidays.json");
JavaScriptSerializer serializer = new JavaScriptSerializer();
var test = serializer.Deserialize<Dictionary<string, Dictionary<string, object>>>(json);
I can't seem to be able to cast the final object in this deserializer to anything meaningful. I have tried a variety of objects, lists, arrays etc but nothing seem to work. I only ever seem to be able to cast it to object.
Ideally I'd like the JSON to be parsed to a meaningful object such as:
public class BankHoliday
{
public DateTime Date { get; set; }
public string Title { get; set; }
public Country CountryCode { get; set; }
public string Notes { get; set; }
public bool Bunting { get; set; }
}
public enum Country
{
EnglandWales,
Scotland,
NorthernIreland
}
I thought this would be fairly simple but I have tried everything. I'm sure it's something simple that I am missing.
Thanks
Don't use JavaScriptSerializer better choice is JSON.NET
On site json2csharp.com you can generate classes from JSON:
public class Event
{
public string title { get; set; }
public string date { get; set; }
public string notes { get; set; }
public bool bunting { get; set; }
}
public class EnglandAndWales
{
public string division { get; set; }
public List<Event> events { get; set; }
}
public class Scotland
{
public string division { get; set; }
public List<Event> events { get; set; }
}
public class NorthernIreland
{
public string division { get; set; }
public List<Event> events { get; set; }
}
public class RootObject
{
[JsonProperty(PropertyName = "england-and-wales")]
public EnglandAndWales EnglandAndWales { get; set; }
public Scotland scotland { get; set; }
[JsonProperty(PropertyName = "northern-ireland")]
public NorthernIreland NorthernIreland { get; set; }
}
And then deserialise it with this way:
RootObject rootObject = JsonConvert.DeserializeObject<RootObject>(output);
EDIT
Added properties in RootObject to handele bad names.
Tested on simplified JSON:
{
"england-and-wales": {
"division": "england-and-wales",
"events": [{
"title": "New Year’s Day",
"date": "2012-01-02",
"notes": "Substitute day",
"bunting": true
},
{
"title": "Good Friday",
"date": "2012-04-06",
"notes": "",
"bunting": false
},
{
"title": "Boxing Day",
"date": "2017-12-26",
"notes": "",
"bunting": true
}]
},
"scotland": {
"division": "scotland",
"events": [{
"title": "2nd January",
"date": "2012-01-02",
"notes": "",
"bunting": true
},
{
"title": "New Year’s Day",
"date": "2012-01-03",
"notes": "Substitute day",
"bunting": true
},
{
"title": "Boxing Day",
"date": "2017-12-26",
"notes": "",
"bunting": true
}]
},
"northern-ireland": {
"division": "northern-ireland",
"events": [{
"title": "New Year’s Day",
"date": "2012-01-02",
"notes": "Substitute day",
"bunting": true
},
{
"title": "St Patrick’s Day",
"date": "2012-03-19",
"notes": "Substitute day",
"bunting": true
},
{
"title": "Boxing Day",
"date": "2017-12-26",
"notes": "",
"bunting": true
}]
}
}
I would greatly encourage you to use json.net lirary
I think you key problème here is that you need to use your type (BankHoliday) in the type definition:
Dictionary<string, <Dictionary<string, BankHoliday>>
Why not just use dynamic?
public IHttpActionResult BankHolidays()
{
var rawJson = string.Empty;
using (var webClient = new WebClient())
{
webClient.Encoding = Encoding.UTF8; // Expected Content-Type response is "application/json; charset=utf-8"
rawJson = webClient.DownloadString("https://www.gov.uk/bank-holidays.json");
}
dynamic json = JsonConvert.DeserializeObject<dynamic>(rawJson);
return Ok(json);
}

Deserialize nested JSON array using RestSharp

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.

Multi-Object JSON, "Cannot deserialize the current JSON object"

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;

Categories

Resources