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; }
}
Related
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
I have the following JSON, and I want to take a list of IDs with its values
For example in LINQ something like this: result.Select(x=>x.id)
I tried this:
var inner = outer["pictures"].Value<JArray>().ToList();
I have a list there but with all attributes but I am not able to select just IDs since it is an anonymous list.
outer
{{
"id": "669654603",
"pictures": [
{
"id": "659745-MLA25600661898_052017",
"url": "http://mla-s2-p.mlstatic.com/659745-MLA25600661898_052017-O.jpg",
"secure_url": "https://mla-s2-p.mlstatic.com/659745-MLA25600661898_052017-O.jpg",
"size": "500x365",
"max_size": "625x457",
"quality": ""
},
{
"id": "908422-MLA25658267858_062017",
"url": "http://mla-s2-p.mlstatic.com/908422-MLA25658267858_062017-O.jpg",
"secure_url": "https://mla-s2-p.mlstatic.com/908422-MLA25658267858_062017-O.jpg",
"size": "47x47",
"max_size": "47x47",
"quality": ""
},
{
"id": "794138-MLA25658267889_062017",
"url": "http://mla-s2-p.mlstatic.com/794138-MLA25658267889_062017-O.jpg",
"secure_url": "https://mla-s2-p.mlstatic.com/794138-MLA25658267889_062017-O.jpg",
"size": "40x40",
"max_size": "40x40",
"quality": ""
}
]
}}
When working with Newtonsoft JSON you can do it like this:
var values = JObject.Parse(jsonString)["pictures"].Select(p => p["id"].Value<string>()).ToList();
In order to be valid your json should not contain double curly brackets:
{
"id": "669654603",
"pictures": [ ... ]
}
You can parse it without additional classes:
var ids = JObject.Parse(json)["pictures"].Select(p => (string)p["id"]);
Output:
[
"659745-MLA25600661898_052017",
"908422-MLA25658267858_062017",
"794138-MLA25658267889_062017"
]
Or you can create several classes to hold your json data:
public class Container
{
public List<Picture> Pictures { get; set; }
}
public class Picture
{
public string Id { get; set; }
// you can add other properties here
}
And use strongly-typed parsing:
var ids = JsonConvert.DeserializeObject<Container>(json).Pictures.Select(p => p.Id);
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 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.
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"
}
]