Reading from, Writing and Appending to JSON files - c#

I have been tryng to parse properly some json files for a while now, but I can't seem to get it right. I've tried many tutorials, and the json.net library but cannot seem to find the right way to go about this. My files all have the same format:
file.json:
{
"Expense": {
"Name": "something",
"Amount": "34.90",
"Due": "28/12/2011",
"Recurrence": "1 Months",
"Paid": "0",
"LastPaid": "01/01/2002"
}
}
{
"Expense": {
"Name": "OneTel Mobile Bill",
"Amount": "39.90",
"Due": "28/12/2011",
"Recurrence": "1 Months",
"Paid": "0",
"LastPaid": "01/01/2002"
}
}
{
"Expense": {
"Name": "some other Bill",
"Amount": "44.90",
"Due": "28/12/2011",
"Recurrence": "1 Months",
"Paid": "0",
"LastPaid": "01/01/2002"
}
}
Now, I have two problems here. But first, I know how to write json files. So that's not a problem for me. But my two problems are:
How to read the json string/file like:
(psuedocode)
FOREACH VAR EXPENSE IN EXPENSES
OUTPUT EXPENSE.NAME
OUTPUT EXPENSE.AMOUNT
etc etc...
And my second problem, is:
How to append a whole new "Expense" to an existing json file?
I would really appreciate your help on this.
Thank you
I am writing the json to the file like so:
//Create the Json file and save it with WriteToFile();
JObject jobject =
new JObject(
new JProperty("Expense",
new JObject(
new JProperty("Name", NameTextBox.Text),
new JProperty("Amount", AmountTextBox.Text),
new JProperty("Due", DueTextBox.Text),
new JProperty("Recurrence", EveryTextBox.Text + " " + EveryComboBox.SelectionBoxItem),
new JProperty("Paid", "0"),
new JProperty("LastPaid", "Never")
)
)
);
try
{
WriteToFile(Expenses, jobject.ToString());
// Close the flyout now.
this.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
}
catch (Exception exception)
{
Debug.Write(exception.Message);
}

I think you would have a much easier time if you created an Expense class and then serialized and read a collection of Expense objects (i.e. List<Expense>).
public class Expense
{
public string Name { get; set; }
public decimal Amount { get; set; }
public DateTime Due { get; set; }
public string Recurrence { get; set; }
public decimal Paid { get; set; }
public DateTime LastPaid{ get; set; }
}
public class ExpenseCollection : System.Collections.Generic.List<Expense>
{
}
You could then use the builtin JavaScriptSerializer class.
Rough code to create the JSON:
ExpenseCollection cExpenses = new ExpenseCollection();
// ToDo: Fill the expenses collection
var sJSON = (new System.Web.Script.Serialization.JavaScriptSerializer).Serialize(cExpenses);
// ToDo: Write sJSON to a file
And to read it (note that this may need some tweaking):
string sJSON;
// ToDo: Read the json from a file
ExpenseCollection cExpenses = (new System.Web.Script.Serialization.JavaScriptSerializer).Deserialize<ExpenseCollection>(sJSON);
// ToDo: Write sJSON to a file

I believe your JSON is formatted incorrectly, using the serialize method mentioned by #Competent_tech it would produce a result something like:
"Expense": [
{
"Name": "something",
"Amount": "34.90",
"Due": "28/12/2011",
"Recurrence": "1 Months",
"Paid": "0",
"LastPaid": "01/01/2002"
}
{
"Name": "OneTel Mobile Bill",
"Amount": "39.90",
"Due": "28/12/2011",
"Recurrence": "1 Months",
"Paid": "0",
"LastPaid": "01/01/2002"
}
{
"Name": "some other Bill",
"Amount": "44.90",
"Due": "28/12/2011",
"Recurrence": "1 Months",
"Paid": "0",
"LastPaid": "01/01/2002"
}
]

Related

Selected JSON data to c# object [duplicate]

This question already has answers here:
How can I deserialize JSON with C#?
(19 answers)
Closed 8 months ago.
{
"name": "India",
"topLevelDomain": [".in"],
"alpha2Code": "IN",
"alpha3Code": "IND",
"callingCodes": ["91"],
"capital": "New Delhi",
"altSpellings": ["IN", "Bhārat", "Republic of India", "Bharat Ganrajya"],
"subregion": "Southern Asia",
"region": "Asia",
"population": 1380004385,
"latlng": [20.0, 77.0],
"demonym": "Indian",
"area": 3287590.0,
"gini": 35.7,
"timezones": ["UTC+05:30"],
"borders": ["AFG", "BGD", "BTN", "MMR", "CHN", "NPL", "PAK", "LKA"],
"nativeName": "भारत",
"numericCode": "356",
"flags": {
"svg": "https://flagcdn.com/in.svg",
"png": "https://flagcdn.com/w320/in.png"
},
"currencies": [{ "code": "INR", "name": "Indian rupee", "symbol": "₹" }],
"languages": [
{
"iso639_1": "hi",
"iso639_2": "hin",
"name": "Hindi",
"nativeName": "हिन्दी"
},
{
"iso639_1": "en",
"iso639_2": "eng",
"name": "English",
"nativeName": "English"
}
],
"translations": {
"br": "Índia",
"pt": "Índia",
"nl": "India",
"hr": "Indija",
"fa": "هند",
"de": "Indien",
"es": "India",
"fr": "Inde",
"ja": "インド",
"it": "India",
"hu": "India"
},
"flag": "https://flagcdn.com/in.svg",
"regionalBlocs": [
{
"acronym": "SAARC",
"name": "South Asian Association for Regional Cooperation"
}
],
"cioc": "IND",
"independent": true
}
This is my JSON data.From this I need to convert
name
population
area
altSpellings
these values to c#
Using the Newtonsoft.Json library you can load the JSON content into a JObject and treat it like a dictionary where the property names are the key values like so:
//Load the JSON into a JObject
var json = ...
var jsonObject = JObject.Parse(json);
//Pull out the property values using the name as a key
var name = jsonObject["name"].ToString();
var population = int.Parse(jsonObject["population"].ToString());
var area = jsonObject["area"].ToString();
var altSpellings = new List<string>();
foreach (var altSpelling in (JArray)jsonObject["altSpellings"])
altSpellings.Add(altSpelling.ToString());
This is a quick way to get the values out without having to create concrete types to deserialise into. If you happen to have a class that maps onto this JSON structure (json2csharp can be handy here) then you could instead use JsonConvert.DeserializeObject<T> instead to deserialise into an instance of that type where you can access the fields directly.
you can create a class with the properties you need
using Newtonsoft.Json;
Data data = JsonConvert.DeserializeObject<Data>(json);
string name = data.Name; // India
result
{
"name": "India",
"population": 1380004385,
"area": 3287590,
"altSpellings": [
"IN",
"Bhārat",
"Republic of India",
"Bharat Ganrajya"
]
}
class
public partial class Data
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("population")]
public long Population { get; set; }
[JsonProperty("area")]
public long Area { get; set; }
[JsonProperty("altSpellings")]
public List<string> AltSpellings { get; set; }
}

deserialize a dynamic json object to a class

I'm working with an external API to get some product information, the end points return some data in a static structure and others in dynamic depending on the product I'm inquiring.
For example if I'm requesting data for a soap I get the following JSON:
{ "id": 4623,
"brand": "Fa",
"category": "Cleansing/Washing/Soap – Body",
"photos": {
"name": "Photos",
"value": [ "https//test.com/1jpg"
]
},
"productname": {
"name": "Product Name",
"value": "Fa Shower Cream Yoghurt Vanilla Honey"
},
"warningstatement": {
"name": "Warning Statement",
"value": "Avoid contact with eyes."
},
"consumerusageinstructions": {
"name": "Consumer Usage Instructions",
"value": "Apply directly on skin."
}
and if I'm inquiring about a cheese I get the following JSON:
{
"id": 10838,
"brand": "Domty",
"category": "Cheese",
"photos": {
"name": "Photos",
"value": [ "https://test.com/2.jpg"
]
},
"productname": {
"name": "Product Name",
"value": "Domty White Low Salt Cheese"
},
"description": {
"name": "1312",
"value": "Highest premium quality"
},
"netcontent": {
"name": "Net Content",
"value": "900 gm"
}
and it goes on for every product they offer. I've no problem deserializing the static data like photos array, product name, brand, and id since they are applicable to every product, but the other dynamic properties are the ones I'm concerned about. Is there a way to deserialize to a class like this:
public class Info {
property string key { get; set;} // to hold description, consumerusageinstructions or what every key
property string name { get; set;}
property string value { get; set;}
}
and then add a collection of the class info to my product model?
One way is just to parse the Json and look at the actual entities: this example uses Json.Net:
var parsed = JObject.Parse(json);
var properties = parsed.Children().Cast<JProperty>();
foreach (var property in properties) {
// an alternative here would be to just have a list of names to ignore
if (!(property.Value is JObject jObject)) {
// skip the simple property/value pairs
continue;
}
if (property.Name == "productname") {
// skip product name
continue;
}
if (property.Value["value"] is JArray) {
// skip photos
continue;
}
// Add to ProductModel instance
Console.WriteLine($"{property.Name} => {property.Value["name"]} = {property.Value["value"]}");
}
Outputs:
warningstatement => Warning Statement = Avoid contact with eyes.
consumerusageinstructions => Consumer Usage Instructions = Apply directly on skin.
description => 1312 = Highest premium quality
netcontent => Net Content = 900 gm

How do I make JSON accessible from inside of many arrays?

I hope it doesn't seem like I want to be spoon-fed at this rate of asking questions, but this next question is a bit more difficult and I don't understand how to solve this at all.
{
"results": [
{
"id": "5d914028302b840050acbe62",
"picture": "https://utellyassets9-1.imgix.net/api/Images/4e4d50a0040fd4500193202edbafce6a/Redirect",
"name": "BoJack Horseman",
"locations": [
{
"icon": "https://utellyassets7.imgix.net/locations_icons/utelly/black_new/NetflixIVAUS.png?w=92&auto=compress&app_version=ae3576e2-0796-4eda-b953-80cadc8e2619_eww2020-05-08",
"display_name": "Netflix",
"name": "NetflixIVAUS",
"id": "5d81fe2fd51bef0f42268f0f",
"url": "https://www.netflix.com/title/70298933"
}
],
"provider": "iva",
"weight": 5654,
"external_ids": {
"iva_rating": null,
"imdb": {
"url": "https://www.imdb.com/title/tt3398228",
"id": "tt3398228"
},
"tmdb": {
"url": "https://www.themoviedb.org/movie/61222",
"id": "61222"
},
"wiki_data": {
"url": "https://www.wikidata.org/wiki/Q17733404",
"id": "Q17733404"
},
"iva": {
"id": "783721"
},
"gracenote": null,
"rotten_tomatoes": null,
"facebook": null
}
},
{
"id": "5e2ce07890c0e033a487e3d2",
"picture": "https://utellyassets9-1.imgix.net/api/Images/326d2853ff6885c41b9adb05278017f6/Redirect",
"name": "Dragon Ball Z: Bojack Unbound",
"locations": [
{
"icon": "https://utellyassets7.imgix.net/locations_icons/utelly/black_new/iTunesIVAUS.png?w=92&auto=compress&app_version=ae3576e2-0796-4eda-b953-80cadc8e2619_eww2020-05-08",
"display_name": "iTunes",
"name": "iTunesIVAUS",
"id": "5d80a9a5d51bef861d3740d3",
"url": "https://itunes.apple.com/us/movie/dragon-ball-z-bojack-unbound-subtitled-original-version/id1381102560"
}
],
"provider": "iva",
"weight": 0,
"external_ids": {
"iva_rating": null,
"imdb": {
"url": "https://www.imdb.com/title/tt0142238",
"id": "tt0142238"
},
"tmdb": {
"url": "https://www.themoviedb.org/movie/39105",
"id": "39105"
},
"wiki_data": {
"url": "https://www.wikidata.org/wiki/Q1255010",
"id": "Q1255010"
},
"iva": {
"id": "406043"
},
"gracenote": null,
"rotten_tomatoes": null,
"facebook": null
}
}
],
"updated": "2020-05-08T05:19:01+0100",
"term": "Bojack",
"status_code": 200,
"variant": "ivafull"
}
Alright, so the first 0: represents the option that the API returned (so in this case it's bojack horseman) and any following number (if it said 1: afterward) would be a different result.
I tried writing a second class to deal with results (resultoverall) that is controlled by the overall,
public class overall
{
[JsonProperty("status_code")]
public string status_code { get; set; }
[JsonProperty("term")]
public string term { get; set; }
[JsonProperty("updated")]
public string updated { get; set; }
[JsonProperty("results")]
public List<resultoverall> results { get; set; }
}
public partial class resultoverall
{
[JsonProperty("name")]
public string name { get; set; }
}
and tried
overall BestGamer = JsonConvert.DeserializeObject<overall>(thicky);
List<overall> ObjOrderList = JsonConvert.DeserializeObject<List<overall>>(thicky);
to be able to access data from both outside of the 0: and inside of the 0: (BestGamer / overall handles outside, resultoverall / Tapioca handles inside, but I get error about the type requiring a JSON array
even though it is already in an array format.
How do I set this up to access data inside of the 0:, for each number that appears (so if there is 2 options I can access info from both?
Using Console.WriteLine(BestGamer.updated); correctly gives me the info from the overall group, but using the Console.WriteLine(BestGamer.results.name); does not work, saying:
Error CS1061 'extension method 'name' accepting a first argument of type 'List<resultoverall>' could be found (are you missing a using directive or an assembly reference?)
You have a JSON object, not an array. Therefore you can't deserialize it as an array. That is correct. You are already deserializing it to an object. So after
overall BestGamer = JsonConvert.DeserializeObject<overall>(thicky);
You can access the objects in results like
var numberOfResults = BestGamer.results.Count;
var firstResult = BestGamer.results[0];
var firstResultsName = BestGamer.results[0].name;
// or loop through the results
foreach (var item in BestGamer.results)
{
// item.Name gives you the name of the current result
}

Search for a nested value inside of a JSON.net object in C#

I've got a JSON stream coming back from a server, and I need to search for a specific value of the node "ID" using JSON.net to parse the data.
And I can almost make it work, but not quite because the results coming back are deeply nested in each other -- this is due to the fact that I'm getting a folder structure back. I've boiled the JSON down to a much simpler version. I'm getting this:
{
"data": {
"id": 0,
"name": "",
"childFolders": [{
"id": 19002,
"name": "Locker",
"childFolders": [{
"id": 19003,
"name": "Folder1",
"childFolders": [],
"childComponents": [{
"id": 19005,
"name": "route1",
"state": "STOPPED",
"type": "ROUTE"
}]
}, {
"id": 19004,
"name": "Folder2",
"childFolders": [],
"childComponents": [{
"id": 19008,
"name": "comm1",
"state": "STOPPED",
"type": "COMMUNICATION_POINT"
}, {
"id": 19006,
"name": "route2",
"state": "STOPPED",
"type": "ROUTE"
}, {
"id": 19007,
"name": "route3",
"state": "STOPPED",
"type": "ROUTE"
}]
}],
"childComponents": []
}],
"childComponents": []
},
"error": null
}
I can almost get there by going:
var objects = JObject.Parse(results);
var subobjects = objects["data"]["childFolders"][0]["childFolders"][1];
I can see in the debug view that it'll parse the object, but won't let me search within.
My ultimate goal is to be able to search for "route3" and get back 19007, since that's the ID for that route. I've found some results, but all of them assume you know how far nested the object is. The object I'm searching for could be 2 deep or 20 deep.
My ultimate goal is to be able to search for "route3" and get back 19007
You can use linq and Descendants method of JObject to do it:
var dirs = JObject.Parse(json)
.Descendants()
.Where(x=>x is JObject)
.Where(x=>x["id"]!=null && x["name"]!=null)
.Select(x =>new { ID= (int)x["id"], Name = (string)x["name"] })
.ToList();
var id = dirs.Find(x => x.Name == "route3").ID;
You can use the SelectToken or SelectTokens functions to provide a JPath to search for your desired node. Here is an example that would provide you the route based on name:
JObject.Parse(jsonData)["data"].SelectToken("$..childComponents[?(#.name=='route3')]")
You can find more documentation on JPath here
Simply write a recursive function:
private Thing FindThing(Thing thing, string name)
{
if (thing.name == name)
return thing;
foreach (var subThing in thing.childFolders.Concat(thing.childComponents))
{
var foundSub = FindThing(subThing, name);
if (foundSub != null)
return foundSub;
}
return null;
}
class RootObject
{
public Thing data { get; set; }
}
class Thing
{
public int id { get; set; }
public string name { get; set; }
public List<Thing> childFolders { get; set; } = new List<Thing>();
public List<Thing> childComponents { get; set; } = new List<Thing>();
}
And using it:
var obj = JsonConvert.DeserializeObject<RootObject>(jsonString);
var result = FindThing(obj.data, "route3");

How make array insert array json in web service C#

How can I create a JsonArray with a child data object array? I am using Web service and C#.
I want the result of the JsonArray to look like the following:
[{
"name": "Deadpool",
"url": {
"small": "http://api.android.info/images/small/deadpool.jpg",
"medium": "http://api.android.info/images/medium/deadpool.jpg",
"large": "http://api.android.info/images/large/deadpool.jpg"
},
"time": "February 12, 2016"
},
{
"name": "The Jungle Book",
"url": {
"small": "http://api.android.info/images/small/book.jpg",
"medium": "http://api.android.info/images/medium/book.jpg",
"large": "http://api.android.info/images/large/book.jpg"
},
"time": "April 15, 2016"
},
{
"name": "X-Men: Apocalypse",
"url": {
"small": "http://api.android.info/images/small/xmen.jpg",
"medium": "http://api.android.info/images/medium/xmen.jpg",
"large": "http://api.android.info/images/large/xmen.jpg"
},
"time": "May 27, 2016"
}]
First, create the models that can output the given data. You need a MovieModel, a movie can have multiple image sizes and urls stored, we use a dictionary for this.
UPDATED
MovieModel.cs
public class MovieModel
{
public string Name { get; set; }
public Dictionary<string,string> Url { get; set; }
public string Time { get; set; }
}
Now you need to install Newtonsoft.Json from Nuget packages. Then import it.
using Newtonsoft.Json;
Initialize the model and convert to Json using SerializeObject() method.
var movieList = new List<MovieModel>
{
new MovieModel
{
MovieName = "Deadpool",
Time = DateTime.UtcNow.ToString("t"),
Url = new Dictionary<string, string>
{
{ "small", "http://api.android.info/images/small/deadpool.jpg" },
{ "medium", "http://api.android.info/images/medium/deadpool.jpg" }
}
}
// .. add more movies .. //
};
// convert to camelcase and set indentation
var output = JsonConvert.SerializeObject(
movieList,
Formatting.Indented,
new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
}
);
// testing output on console
Console.WriteLine(output);
In a real application, you would create Movie instances by getting data from a database, not initializing it for yourself as used in this example.

Categories

Resources