I am trying to build a function where a user can upload a json file.
Each row in the json file can have a different nr of properties(i.e. columns).
5 of these properties are always the same so I want those to be deserialized to an object. The rest of the properties have to go into a dictionary or something.
Here is a json example:
[{
"Projekt": "Bakker Bouw Service",
"Ruimte": "Hoofdgebouw",
"Apparaat": {
"project": "Bosboom001",
"versie": "812"
},
"Apparaat naam": "",
"Status": "Goedgekeurd",
"Testname1": "",
"Testname3": "2000-01-04T10:37:00+01:00",
"Testname7": "2001-01-03T00:00:00+01:00"
}, {
"Projekt": "Bakker Bouw Service",
"Ruimte": "Hoofdgebouw",
"Apparaat": {
"project": "Vlaams003",
"versie": "713"
},
"Apparaat naam": "",
"Status": "Goedgekeurd",
"Testname1": "Slecht",
"Testname7": "2000-01-04T10:37:00+01:00",
"Testname9": "2001-01-03T00:00:00+01:00",
"Testname16": "18MOhm",
"Testname23": "OK"
}, {
"Projekt": "Bakker Bouw Service",
"Ruimte": "Hoofdgebouw",
"Apparaat": {
"project": "Vlaams017",
"versie": "73"
},
"Apparaat naam": "GDR34Z5",
"Status": "Afgekeurd",
"Testname7": "2000-01-04T10:37:00+01:00",
"Testname10": "0,012mA",
"Testname16": "200MOhm",
"Testname23": "200MOhm",
"Testname25": "Afgekeurd",
"Testname31": "0,01mA"
}
]
Here is the class to deserialze to:
public class KeuringRegel
{
public string Projekt { get; set; }
public string Ruimte { get; set; }
public Apparaat Apparaat { get; set; }
[JsonProperty(PropertyName = "Apparaat naam")]
public string Apparaatnaam { get; set; }
public string Status { get; set; }
public Dictionary<string, object> testNames { get; set; }
}
public class Apparaat
{
public string project { get; set; }
public string versie { get; set; }
}
And here is the controller
public IActionResult Upload(IFormFile file)
{
string fileContent = null;
using (var reader = new StreamReader(file.OpenReadStream()))
{
fileContent = reader.ReadToEnd();
}
List<KeuringRegel> keuringRegelList = JsonConvert.DeserializeObject<List<KeuringRegel>>(fileContent);
//More stuff here
}
The json successfully deserializes but the testNames value is always null. I understand why, because there is no testNames property in the Json file. However, how do I achieve what I want? I am no Json expert.
One way you can do this, assuming that there is only testNameNNNN entries as supplemental values, is to use the JsonExtensionDataAttribute like this:
public class KeuringRegel
{
public string Projekt { get; set; }
public string Ruimte { get; set; }
public Apparaat Apparaat { get; set; }
[JsonProperty(PropertyName = "Apparaat naam")]
public string Apparaatnaam { get; set; }
public string Status { get; set; }
[JsonExtensionData()]
public Dictionary<string, object> testNames { get; set; }
}
This will give you the values whos don't fall into one of the other properties:
It's a bit of a "blunt instrument" but you could always perform some post-processing on the returned instances of KeuringRegel to remove any errant entries from testNames (i.e. things that don't match the pattern testNameNNNN).
If your JSON does contain things that don't match the pattern testNameNNNN which would therefore get included, you could implement a custom class for the testNames property:
public class KeuringRegel
{
public string Projekt { get; set; }
public string Ruimte { get; set; }
public Apparaat Apparaat { get; set; }
[JsonProperty(PropertyName = "Apparaat naam")]
public string Apparaatnaam { get; set; }
public string Status { get; set; }
[JsonExtensionData()]
public TestNames testNames { get; set; }
}
public class TestNames : Dictionary<string, object>
{
public new void Add(string key, object value)
{
if (key.StartsWith("testname", StringComparison.OrdinalIgnoreCase))
{
base.Add(key, value);
}
}
}
This will check each item that is added to the testNames dictionary and prevent its addition if (as in my comment where I had an item in the JSON of "badgerBadgetCatCat": 3) it doesn't match the pattern.
Here u are full example
internal class Program
{
private static void Main(string[] args)
{
var str = #"[{
""Projekt"": ""Bakker Bouw Service"",
""Ruimte"": ""Hoofdgebouw"",
""Apparaat"": {
""project"": ""Bosboom001"",
""versie"": ""812""
},
""Apparaat naam"": """",
""Status"": ""Goedgekeurd"",
""Testname1"": """",
""Testname3"": ""2000-01-04T10:37:00+01:00"",
""Testname7"": ""2001-01-03T00:00:00+01:00""
}, {
""Projekt"": ""Bakker Bouw Service"",
""Ruimte"": ""Hoofdgebouw"",
""Apparaat"": {
""project"": ""Vlaams003"",
""versie"": ""713""
},
""Apparaat naam"": """",
""Status"": ""Goedgekeurd"",
""Testname1"": ""Slecht"",
""Testname7"": ""2000-01-04T10:37:00+01:00"",
""Testname9"": ""2001-01-03T00:00:00+01:00"",
""Testname16"": ""18MOhm"",
""Testname23"": ""OK""
}, {
""Projekt"": ""Bakker Bouw Service"",
""Ruimte"": ""Hoofdgebouw"",
""Apparaat"": {
""project"": ""Vlaams017"",
""versie"": ""73""
},
""Apparaat naam"": ""GDR34Z5"",
""Status"": ""Afgekeurd"",
""Testname7"": ""2000-01-04T10:37:00+01:00"",
""Testname10"": ""0,012mA"",
""Testname16"": ""200MOhm"",
""Testname23"": ""200MOhm"",
""Testname25"": ""Afgekeurd"",
""Testname31"": ""0,01mA""
}
]";
var sw = Stopwatch.StartNew();
var result = Mapper.Map(str);
sw.Stop();
Console.WriteLine($"Deserialized at {sw.ElapsedMilliseconds} ms ({sw.ElapsedTicks} tiks)");
}
public static class Mapper
{
static Mapper()
{
List<string> names = new List<string>();
IEnumerable<PropertyInfo> p = typeof(KeuringRegel).GetProperties().Where(c => c.CanRead && c.CanWrite);
foreach (var propertyInfo in p)
{
var attr = propertyInfo.GetCustomAttribute<JsonPropertyAttribute>();
names.Add(attr != null ? attr.PropertyName : propertyInfo.Name);
}
Properties = names.ToArray();
}
private static string[] Properties { get; }
public static KeuringRegel[] Map(string str)
{
var keuringRegels = JsonConvert.DeserializeObject<KeuringRegel[]>(str);
var objs = JsonConvert.DeserializeObject(str) as IEnumerable;
var objectList = new List<JObject>();
foreach (JObject obj in objs)
objectList.Add(obj);
for (var i = 0; i < keuringRegels.Length; i++)
{
keuringRegels[i].testNames = new Dictionary<string, object>();
foreach (var p in objectList[i].Children().OfType<JProperty>().Where(c => !Properties.Contains(c.Name)).ToArray())
keuringRegels[i].testNames.Add(p.Name, p.Value);
}
return keuringRegels;
}
}
public class KeuringRegel
{
public string Projekt { get; set; }
public string Ruimte { get; set; }
public Apparaat Apparaat { get; set; }
[JsonProperty(PropertyName = "Apparaat naam")]
public string Apparaatnaam { get; set; }
public string Status { get; set; }
public Dictionary<string, object> testNames { get; set; }
}
public class Apparaat
{
public string project { get; set; }
public string versie { get; set; }
}
}
Related
I have a below json, I want to loop the items inside the attribute CheckingUrls.
{
"Root": {
"Urls": {
"CheckingUrls": [
{
"API Management": {
"url": ".azure-api.net",
"displayurl": "*.azure-api.net"
},
"Log Analytics": {
"url": "1.ods.opinsights.azure.com",
"displayurl": "*.ods.opinsights.azure.com"
}
}
]
}
}
}
Here are the C# class
public class Root
{
Urls Urls { get; set; }
}
public class Urls
{
public List<CheckingUrls> CheckingUrls { get; set; }
}
public class CheckingUrls
{
[JsonProperty("API Management")]
public UrlDetails APIManagement { get; set; }
[JsonProperty("Log Analytics")]
public UrlDetails LogAnalytics { get; set; }
}
public class UrlDetails
{
[JsonProperty("url")]
public string url { get; set; }
[JsonProperty("displayurl")]
public string displayurl { get; set; }
}
I am trying to convert it into c# object using the below code
var content = File.ReadAllText(jsonstring);
var settings = JsonConvert.DeserializeObject<Root>(content);
I am getting APIManagement and LogAnalytics as properties in the result. Is it possible to get these as List, so that I can loop the contents without hardcoding the properties in code.
Why I need solution: We might add new child to CheckingUrls and we do not want to change the c# code everytime when we change JSON.
Use a C# Dictionary when you want to convert a JSON Object to C# when you don't have a concrete type. CheckingUrls is already an array, so you end up with
public List<Dictionary<string, UrlDetails>> CheckingUrls { get; set; }
The key of a Dictionary entry is the property name in the array element (like "API Management"), and the value is the object that contains the url and displayurl properties.
This eliminates the need for the CheckingUrls C# class.
If you want a List, you can create a CheckingUrls class
List<CheckingUrls> checkingUrlsList = JObject.Parse(json)
.SelectToken("Root.Urls.CheckingUrls")
.SelectMany(jo => ((JObject)jo).Properties()
.Select(p => new CheckingUrls
{
UrlName = p.Name,
UrlDetails = new UrlDetails
{
url = (string)p.Value["url"],
displayurl = (string)p.Value["displayurl"]
}
}
)).ToList();
public class CheckingUrls
{
public string UrlName { get; set; }
public UrlDetails UrlDetails { get; set; }
}
public class UrlDetails
{
public string url { get; set; }
public string displayurl { get; set; }
}
output ( in a json format)
[
{
"UrlName": "API Management",
"UrlDetails": {
"url": ".azure-api.net",
"displayurl": "*.azure-api.net"
}
},
{
"UrlName": "Log Analytics",
"UrlDetails": {
"url": "1.ods.opinsights.azure.com",
"displayurl": "*.ods.opinsights.azure.com"
}
}
]
but if you changed your mind to a Dictionary
Dictionary<string, UrlDetails> checkingUrlsDict = JObject.Parse(json)
.SelectToken("Root.Urls.CheckingUrls")
.Select(jo => jo.ToObject<Dictionary<string, UrlDetails>>())
.FirstOrDefault();
Coming here after learning about C# classes Constructors and ArrayLists so that not to put a completely dumb question here :)
I'm trying to Deserialize below Nested Lists of JSON returned from an API GET call as below:
I've been able to get the value from the empArra (Field: Emp), but subsequent lists like yearArray, prod and sale are not returning there values.
Can you please look into the below code that where is it doing wrong?
JSON
[
{
"employee":"156718100",
"availability":[
{
"year":2018,
"sales":{
"availability":"Maybe",
"reason":""
},
"prod":{
"availability":"Maybe",
"reason":""
}
},
{
"year":2019,
"sales":{
"availability":"Maybe",
"reason":""
},
"prod":{
"availability":"Maybe",
"reason":""
}
},
{
"year":2020,
"sales":{
"availability":"Maybe",
"reason":""
},
"top":{
"availability":"Maybe",
"reason":""
}
},
{
"year":2021,
"sales":{
"availability":"Maybe",
"reason":""
},
"prod":{
"availability":"Maybe",
"reason":""
}
}
]
}
]
Classes
public class sale
{
public string SaleAvailability { get; set; }
public string SaleReason { get; set; }
public sale(string pSaleAvailability, string pSaleReason)
{
this.SaleAvailability = pSaleAvailability;
this.SaleReason = pSaleReason;
}
public override string ToString()
{
return string.Format("{0} {1}", SaleAvailability, SaleReason);
}
}
public class prod
{
public string ProdAvailability { get; set; }
public string ProdReason { get; set; }
public prod(string pProdAvailability, string pProdReason)
{
this.ProdAvailability = pProdAvailability;
this.ProdReason = pProdReason;
}
public override string ToString()
{
return string.Format("{0} {1}", ProdAvailability, ProdReason);
}
}
public class yearArray
{
public int Year { get; set; }
public yearArray(int pYear)
{
this.Year = pYear;
}
List<sale> Sale { get; set; } = new List<sale>();
List<prod> Prod { get; set; } = new List<prod>();
}
public class rootAvailability
{
public List<yearArray> YearArray { get; set; } = new List<yearArray>();
}
public class empArray
{
public string Emp { get; set; }
public List<rootAvailability> RootAvailability { get; set; } = new List<rootAvailability>();
}
public class rootArray
{
public List<empArray> EmpArrays { get; set; } = new List<empArray>();
}
main() method
(After getting the response from API)
IRestResponse response = client.Execute<rootArray>(request);
//Console.WriteLine(response.Content);
List<rootArray> rootArrays = JsonConvert.DeserializeObject<List<rootArray>>(response.Content);
List<empArray> empArrays = JsonConvert.DeserializeObject<List<empArray>>(response.Content);
List<rootAvailability> rootAvailabilities = JsonConvert.DeserializeObject<List<rootAvailability>>(response.Content);
List<yearArray> yearArrays = JsonConvert.DeserializeObject<List<yearArray>>(response.Content);
List<sale> clsSale = JsonConvert.DeserializeObject<List<sale>>(response.Content);
List<prod> clsProd = JsonConvert.DeserializeObject<List<prod>>(response.Content);
foreach (var rootitem in rootArrays)
{
foreach (var emparrayitem in empArrays)
{
Console.WriteLine("NSN: " + emparrayitem.Emp);
foreach (var rootavailabbilitiesitem in rootAvailabilities)
{
foreach (var yearArrayItem in yearArrays)
{
Console.WriteLine("Year: " + yearArrayItem.Year);
foreach (var saleItem in clsSale)
{
Console.WriteLine("SaleAvailability: " + saleItem.SaleAvailability);
Console.WriteLine("SaleReason: " + saleItem.SaleReason);
}
foreach (var prodItem in clsProd)
{
Console.WriteLine("SaleAvailability: " + prodItem.ProdAvailability);
Console.WriteLine("SaleReason: " + prodItem.ProdReason);
}
}
}
}
}
Results
Emp: 159252663
Year: 0
SaleAvailability:
SaleReason:
SaleAvailability:
SaleReason:
You have two problems with your approach:
You want to deserialize the same source over and over again (response.Content) for different class instances. It can be deserialized into one object type: your top level entity.
Your data model does not reflect your data. For example YearArray should have a single Prod and Sale property not a list of them.
You have several options how to fix it. Let me share with you the two most common ones:
With proper naming
Your object model should look like this:
public class Sale
{
public string Availability { get; set; }
public string Reason { get; set; }
}
public class Prod
{
public string Availability { get; set; }
public string Reason { get; set; }
}
public class MidLevel
{
public int Year { get; set; }
public Sale Sales { get; set; }
public Prod Top { get; set; }
}
public class TopLevel
{
public string Employee { get; set; }
public List<MidLevel> Availability { get; set; } = new List<MidLevel>();
}
Then all you need to do is to call the following command:
var result = JsonConvert.DeserializeObject<TopLevel[]>(json);
Now, your result will be populated with all the data.
With JsonProperty
If you don't want to use the same names in your domain model which is used in the json then you can define the mapping between these two worlds via JsonProperty attributes.
Now your domain model can look like this:
public class SalesInformation
{
[JsonProperty(PropertyName = "availability")]
public string Avail { get; set; }
[JsonProperty(PropertyName = "reason")]
public string Reasoning { get; set; }
}
public class ProdInformation
{
[JsonProperty(PropertyName = "availability")]
public string Availability { get; set; }
[JsonProperty(PropertyName = "reason")]
public string Reasoning { get; set; }
}
public class MidLevel
{
[JsonProperty(PropertyName = "year")]
public int AvailYear { get; set; }
[JsonProperty(PropertyName = "sales")]
public SalesInformation SalesInfos { get; set; }
[JsonProperty(PropertyName = "top")]
public ProdInformation ProdInfos { get; set; }
}
public class TopLevel
{
[JsonProperty(PropertyName = "employee")]
public string Emp { get; set; }
[JsonProperty(PropertyName = "availability")]
public List<MidLevel> Availabilities { get; set; } = new List<MidLevel>();
}
The usage would be exactly the same:
var result = JsonConvert.DeserializeObject<TopLevel[]>(json);
UPDATE: How to display data
To represent hierarchy in a console application can be achieved in may ways. Here I will use indentation. I've introduced the following tiny helper method:
public static void WriteWithIndent(int level, string message) => Console.WriteLine("".PadLeft(level * 2) + message);
With this in hand the data visualization could be achieved in the following way:
var result = JsonConvert.DeserializeObject<TopLevel[]>(json);
foreach (var topLevel in result)
{
Console.WriteLine($"Employee: {topLevel.Emp}");
foreach (var midLevel in topLevel.Availabilities)
{
WriteWithIndent(1, $"Year: {midLevel.AvailYear}");
WriteWithIndent(1, "Sales:");
WriteWithIndent(2, $"Avail: {midLevel.SalesInfos.Avail}");
WriteWithIndent(2, $"Reason: {midLevel.SalesInfos.Reasoning}");
WriteWithIndent(1, "Top:");
WriteWithIndent(2, $"Avail: {midLevel.ProdInfos.Avail}");
WriteWithIndent(2, $"Reason: {midLevel.ProdInfos.Reasoning}");
}
}
The printed output will look like this:
Employee: 156718100
Year: 2018
Sales:
Avail: Maybe
Reason:
Top:
Avail: Maybe
Reason:
Year: 2019
Sales:
Avail: Maybe
Reason:
Top:
Avail: Maybe
Reason:
Year: 2020
Sales:
Avail: Maybe
Reason:
Top:
Avail: Maybe
Reason:
Year: 2021
Sales:
Avail: Maybe
Reason:
Top:
Avail: Maybe
Reason:
c# code:-
var handler = new HttpClientHandler();
HttpClient client = new HttpClient(handler);
string result = await client.GetStringAsync(url);
Console.WriteLine(result);
json respose(result):-
{
"accountstab": [
{
"LoginType": "r",
"RepId": 3368,
"RepName": "Aachi's M",
"RepUName": "aachis",
"RepPwd": "aachis123",
"WhlId": null,
"RepLocalId": null,
"WhoName": "Aachi's M",
"WhoTin": "32661034",
"WhoEmail": "hanee#gmail.com"
},
{
"LoginType": "r",
"RepId": 3335,
"RepName": "AL-NAJA M",
"RepUName": "alnaja",
"RepPwd": "chemmad",
"WhlId": null,
"RepLocalId": null,
"WhoName": "AL-NAJA",
"WhoTin": "7222075",
"WhoEmail": "abbas#gmail.com"
}
]
}
model class:
public class RootObject
{
public List<Accountstab> accountstab { get; set; }
}
public class Accountstab
{
public string LoginType { get; set; }
public int RepId { get; set; }
public string RepName { get; set; }
public string RepUName { get; set; }
public string RepPwd { get; set; }
public int? WhlId { get; set; }
public int? RepLocalId { get; set; }
public string WhoName { get; set; }
public string WhoTin { get; set; }
public string WhoEmail { get; set; }
}
I can be done with Newtonsoft.Json dll from NuGet:
using Newtonsoft.Json;
// ...
RootObject json = JsonConvert.DeserializeObject<RootObject>(result);
Usage example:
foreach (var item in json.accountstab)
Console.WriteLine(item.RepUName);
Output:
aachis
alnaja
if there is any problem with string value="null" in json , public string WhoTin { get; set; } this field are null is some records
The error of you json string is not caused by the null, it caused by the ' in the json below.
"RepName": "Aachi's M",
"WhoName": "Aachi's M",
The way you used to deserliaze the json data in Xamarin.forms is correct.
var jsondata = JsonConvert.DeserializeObject<Rootobject>(json);
When you change the ' in json data, it would be okay.
"RepName": "Aachi s M"
"WhoName": "Aachi s M",
I am trying to get a field from the response from the rest services in the Web API we are building. The JSON looks like this:
{
"d": {
"results": [{
"__metadata": {
"id": "Web/Lists(guid'4ddc-41e2-bb44-0f92ad2c0b07')/Items(164)",
"uri": "https://teams.ax.org/sites/js/project/_api/Web/Lists(guid'4ddc-41e2-bb44-0f92ad2c0b07')/Items(164)",
"etag": "\"6\"",
"type": "SP.Data.St_x0020_CdsListItem"
},
"Folder": {
"__deferred": {
"uri": "https://teams.ax.org/sites/js/project/_api/Web/Lists(guid'4ddc-41e2-bb44-0f92ad2c0b07')/Items(164)/Folder"
}
},
"ParentList": {
"__deferred": {
"uri": "https://teams.ax.org/sites/js/project/_api/Web/Lists(guid'4ddc-41e2-bb44-0f92ad2c0b07')/Items(164)/ParentList"
}
},
"PM_x0020_NameId": 220,
"St_x0020_Name": "<div class=\"ExternalClassA14DB0FF86994403B827D91158CF34B0\">KO</div>",
}]
}}
I created these model classes:
public class SharepointDTO
{
public class Metadata
{
[JsonProperty("id")]
public string id { get; set; }
[JsonProperty("uri")]
public string uri { get; set; }
[JsonProperty("etag")]
public string etag { get; set; }
[JsonProperty("type")]
public string type { get; set; }
}
public class Deferred
{
[JsonProperty("uri")]
public string uri { get; set; }
}
public class Folder
{
[JsonProperty("__deferred")]
public Deferred __deferred { get; set; }
}
public class ParentList
{
[JsonProperty("__deferred")]
public Deferred __deferred { get; set; }
}
public class Result
{
[JsonProperty("__metadata")]
public Metadata __metadata { get; set; }
[JsonProperty("Folder")]
public Folder Folder { get; set; }
[JsonProperty("ParentList")]
public ParentList ParentList { get; set; }
[JsonProperty("PM_x0020_NameId")]
public int PM_x0020_NameId { get; set; }
[JsonProperty("St_x0020_Name")]
public string St_x0020_Name { get; set; }
}
public class D
{
[JsonProperty("results")]
public IList<Result> results { get; set; }
}
public class RootObject
{
[JsonProperty("d")]
public D d { get; set; }
}
}
No trying to call the rest service from the Web API and need to get the St_x0020_Name from response and store in a string.
SharepointDTO.RootObject retSharepointobj = await GetfromSharepoint(StNumber);
string StName = retSharepointobj.d.results.St_x0020_Name.ToString();
I am deserializing the JSON in the GetfromSharepoint method like
using (var client_sharePoint = new HttpClient(handler))
{
var response = client_sharePoint.GetAsync(SP_URL).Result;
var responsedata = await response.Content.ReadAsStringAsync();
var returnObj = JsonConvert.DeserializeObject<SharepointDTO.RootObject>(responsedata);
return returnObj;
}
But it throws an error:
'System.Collections.Generic.IList' does not contain a definition for 'St_x0020_Name' and no extension method 'St_x0020_Name' accepting a first argument of type 'System.Collections.Generic.IList' could be found (are you missing a using directive or an assembly reference?)
results is an array, so you have either loop thru like
foreach(var item in retSharepointobj.d.results){
string StName = item.St_x0020_Name.ToString();
}
or get a specific element, for example a first element like:
SharepointDTO.RootObject retSharepointobj = await GetfromSharepoint(StNumber);
string StName = retSharepointobj.d.results[0].St_x0020_Name.ToString();
or you can add an extra check like that
SharepointDTO.RootObject retSharepointobj = await GetfromSharepoint(StNumber);
if(retSharepointobj.d.results.length > 0){
string StName = retSharepointobj.d.results[0].St_x0020_Name.ToString();
}
Shouldn't this line:
string StName = retSharepointobj.d.results.St_x0020_Name.ToString();
Be like this?
string StName = retSharepointobj.d.results.First().St_x0020_Name.ToString();
Here is my json data
{
"found": 501,
"posts": [
{
"ID": 2500,
"site_ID": 1,
"date": "2014-09-26T15:58:23-10:00",
"modified": "2014-09-26T15:58:23-10:00",
"title": "DOD HQ Visitors Parking",
"metadata": [
{
"id": "15064",
"key": "city",
"value": "Honolulu County"
},
{
"id": "15067",
"key": "country",
"value": "US"
},
{
"id": "15062",
"key": "floor_level",
"value": "Ground Floor"
}
]
}
],
"_headers": {
"Date": "Fri, 13 Feb 2015 09:21:55 GMT",
"Content-Type": "application/json"
}
}
I used model class generated from http://json2csharp.com/
public class Metadata
{
public string id { get; set; }
public string key { get; set; }
public string value { get; set; }
}
public class Post
{
public int ID { get; set; }
public int site_ID { get; set; }
public string date { get; set; }
public string modified { get; set; }
public string title { get; set; }
public List<Metadata> metadata { get; set; }
}
public class Headers
{
public string Date { get; set; }
public string __invalid_name__Content-Type { get; set; }
}
public class RootObject
{
public int found { get; set; }
public List<Post> posts { get; set; }
public Headers _headers { get; set; }
}
I don't know if this is the correct way of Parsing JSON array, I want to put the data collected into a ObservableCollection to be used in binding my Listview in XAML Page.
public class SpacesViewModel
{
public ObservableCollection<Space> Spaces { get; set; }
public SpacesViewModel()
{
Spaces = new ObservableCollection<Space>();
this.LoadSpaces();
}
async private void LoadSpaces()
{
var client = new HttpClient();
string json = await client.GetStringAsync("http://localhost/allspaces.json");
var resultObjects = AllChildren(JObject.Parse(json))
.First(c => c.Type == JTokenType.Array && c.Path.Contains("posts"))
.Children<JObject>();
foreach (JObject post in resultObjects)
{
Debug.WriteLine(post["title"]);
foreach (var metadata in post["metadata"])
{
var key = metadata["key"].ToString();
if (key == "city")
Debug.WriteLine(metadata["value"].ToString());
if (key == "street_address")
Debug.WriteLine(metadata["value"].ToString());
}
}
}
private static IEnumerable<JToken> AllChildren(JToken json)
{
foreach (var c in json.Children())
{
yield return c;
foreach (var cc in AllChildren(c))
{
yield return cc;
}
}
}
}
A possible approach is to use the Newtonsofts Json.NET libary. You can easily get it as nuget. After adding the nuget you can simply parse a collection (nested collections are working as well) with:
using Newtonsoft.Json;
...
string json = await client.GetStringAsync("http://localhost/allspaces.json");
List<Post> parsedPosts = JsonConvert.DeserializeObject<List<Post>>(json);
After getting the posts as List, you can add them to your ObservableCollection.