Convert nested/complex JSON to CSV not get actual output - c#

Input json is (The json is little part of real data, real json is very long and more hierarchy. json line more than 30k)
{
"data": {
"getUsers": [
{
"userProfileDetail": {
"userStatus": {
"name": "Expired"
},
"userStatusDate": "2017-04-04T07:48:25+00:00",
"lastAttestationDate": "2019-02-01T03:50:42.6049634-05:00"
},
"userInformation": {
"Id": 13610875,
"lastName": "************",
"suffix": null,
"gender": "FEMALE",
"birthDate": "1970-01-01T00:01:00+00:00",
"ssn": "000000000",
"ethnicity": "INVALID_REFERENCE_VALUE",
"languagesSpoken": null,
"personalEmail": null,
"otherNames": null,
"userType": {
"name": "APN"
},
"primaryuserState": "CO",
"otheruserState": [
"CO"
],
"practiceSetting": "INPATIENT_ONLY",
"primaryEmail": "*****#*****.com"
}
},
{
"userProfileDetail": {
"userStatus": {
"name": "Expired newwwwwwwwwwww"
},
"userStatusDate": "2017-04-04T07:48:25+00:00",
"lastAttestationDate": "2019-02-01T03:50:42.6049634-05:00"
},
"userInformation": {
"Id": 13610875,
"lastName": "************",
"suffix": null,
"gender": "FEMALE",
"birthDate": "1970-01-01T00:01:00+00:00",
"ssn": "000000000",
"ethnicity": "INVALID_REFERENCE_VALUE",
"languagesSpoken": null,
"personalEmail": null,
"otherNames": null,
"userType": {
"name": "APN"
},
"primaryuserState": "CO",
"otheruserState": [
"CO"
],
"practiceSetting": "INPATIENT_ONLY",
"primaryEmail": "*****#*****.com"
}
}
]
}
}
the code is
var obj = JObject.Parse(json);
// Collect column titles: all property names whose values are of type JValue, distinct, in order of encountering them.
var jsonValues = obj.DescendantsAndSelf().OfType<JProperty>().Where(p => p.Value is JValue).GroupBy(p => p.Name).ToList();
var jsonKey = jsonValues.Select(g => g.Key).ToArray();
// Filter JObjects that have child objects that have values.
var parentsWithChildren = jsonValues.SelectMany(g => g).SelectMany(v => v.AncestorsAndSelf().OfType<JObject>().Skip(1)).ToHashSet();
// Collect all data rows: for every object, go through the column titles and get the value of that property in the closest ancestor or self that has a value of that name.
var rows = obj
.DescendantsAndSelf()
.OfType<JObject>()
.Where(o => o.PropertyValues().OfType<JValue>().Any() && (o == obj || !parentsWithChildren.Contains(o))) // Show a row for the root object + objects that have no children.
.Select(o => jsonKey.Select(c => o.AncestorsAndSelf().OfType<JObject>().Select(parent => parent[c])
.Where(v => v is JValue).Select(v => (string)v).FirstOrDefault()).Reverse() // Trim trailing nulls
.SkipWhile(s => s == null).Reverse());
// Convert to CSV
var csvRows = new[] { jsonKey }.Concat(rows).Select(r => string.Join(",", r));
var csv = string.Join("\n", csvRows);
Console.WriteLine(csv);
Here is the output i get:
getUsers_userProfileDetail_userStatus_name,getUsers_userProfileDetail_userStatusDate,getUsers_userProfileDetail_lastAttestationDate,getUsers_userInformation_Id,getUsers_userInformation_lastName,getUsers_userInformation_suffix,getUsers_userInformation_gender,getUsers_userInformation_birthDate,getUsers_userInformation_ssn,getUsers_userInformation_ethnicity,getUsers_userInformation_languagesSpoken,getUsers_userInformation_personalEmail,getUsers_userInformation_otherNames,getUsers_userInformation_userType_name,getUsers_userInformation_primaryuserState,getUsers_userInformation_otheruserState,getUsers_userInformation_practiceSetting,getUsers_userInformation_primaryEmail
Expired,04/04/2017 13:18:25,02/01/2019 14:20:42
APN,,,13610875,************,,FEMALE,01/01/1970 05:31:00,000000000,INVALID_REFERENCE_VALUE,,,,CO,INPATIENT_ONLY,*****#*****.com
here userType > name not column is not in correct place and otheruserState array not come in output.
Anyone can help me?

Following process is what I would recommend since it does not skip the null values and doesnt throw errors if there are nulls. Process below creates a csv formatted string for each of the user in the json and writes down a string.empty for any null value.
List of strings are converted to | delimited since its going in a comma delimited format. You should update all the classes and use Capital first letter in attribute names. I am simply pasting what I got from json2csharp site.
Get Classes for Json
I used json2csharp site to convert your json to classes. Once i got the classes, i used an override method on GetUser to convert the user data to string.... then used that information to print it.
Classes for the Json
public class UserStatus
{
public string name { get; set; }
}
public class UserProfileDetail
{
public UserStatus userStatus { get; set; }
public DateTime userStatusDate { get; set; }
public DateTime lastAttestationDate { get; set; }
}
public class UserType
{
public string name { get; set; }
}
public class UserInformation
{
public int Id { get; set; }
public string lastName { get; set; }
public string suffix { get; set; }
public string gender { get; set; }
public DateTime birthDate { get; set; }
public string ssn { get; set; }
public string ethnicity { get; set; }
public List<string> languagesSpoken { get; set; }
public string personalEmail { get; set; }
public List<string> otherNames { get; set; }
public UserType userType { get; set; }
public string primaryuserState { get; set; }
public List<string> otheruserState { get; set; }
public string practiceSetting { get; set; }
public string primaryEmail { get; set; }
}
public class GetUser
{
public override string ToString()
{
List<string> userData = new List<string>
{
userProfileDetail.userStatus.name,
userProfileDetail.userStatusDate.ToString(),
userProfileDetail.lastAttestationDate.ToString(),
userInformation.Id.ToString(),
userInformation.lastName,
userInformation.suffix?? string.Empty ,
userInformation.gender?? string.Empty ,
userInformation.birthDate.ToString(),
userInformation.ssn?? string.Empty ,
userInformation.ethnicity?? string.Empty ,
string.Join("|", userInformation.languagesSpoken?? new List<string>()),
userInformation.personalEmail?? string.Empty ,
string.Join("|", userInformation.otherNames?? new List<string>() ),
userInformation.userType.name?? string.Empty ,
userInformation.primaryuserState?? string.Empty ,
string.Join("|", userInformation.otheruserState),
userInformation.practiceSetting?? string.Empty ,
userInformation.primaryEmail
};
return string.Join(",", userData);
}
public UserProfileDetail userProfileDetail { get; set; }
public UserInformation userInformation { get; set; }
}
public class Data
{
public List<GetUser> getUsers { get; set; }
}
public class RootObject
{
public string GetHeader()
{
return "getUsers_userProfileDetail_userStatus_name,getUsers_userProfileDetail_userStatusDate,getUsers_userProfileDetail_lastAttestationDate,getUsers_userInformation_Id,getUsers_userInformation_lastName,getUsers_userInformation_suffix,getUsers_userInformation_gender,getUsers_userInformation_birthDate,getUsers_userInformation_ssn,getUsers_userInformation_ethnicity,getUsers_userInformation_languagesSpoken,getUsers_userInformation_personalEmail,getUsers_userInformation_otherNames,getUsers_userInformation_userType_name,getUsers_userInformation_primaryuserState,getUsers_userInformation_otheruserState,getUsers_userInformation_practiceSetting,getUsers_userInformation_primaryEmail";
}
public Data data { get; set; }
}
How to use the classes above
string json = File.ReadAllLines("locationOfJson");
var rootObject = JsonConvert.DeserializeObject<RootObject>(json);
Console.WriteLine(rootObject.GetHeader()); // Prints Header
foreach (var user in rootObject.data.getUsers)
{
Console.WriteLine(user.ToString()); // Print Each User.
}
Output
getUsers_userProfileDetail_userStatus_name,getUsers_userProfileDetail_userStatusDate,getUsers_userProfileDetail_lastAttestationDate,getUsers_userInformation_Id,getUsers_userInformation_lastName,getUsers_userInformation_suffix,getUsers_userInformation_gender,getUsers_userInformation_birthDate,getUsers_userInformation_ssn,getUsers_userInformation_ethnicity,getUsers_userInformation_languagesSpoken,getUsers_userInformation_personalEmail,getUsers_userInformation_otherNames,getUsers_userInformation_userType_name,getUsers_userInformation_primaryuserState,getUsers_userInformation_otheruserState,getUsers_userInformation_practiceSetting,getUsers_userInformation_primaryEmail
Expired,4/4/2017 3:48:25 AM,2/1/2019 3:50:42 AM,13610875,************,,FEMALE,12/31/1969 7:01:00 PM,000000000,INVALID_REFERENCE_VALUE,,,,APN,CO,CO,INPATIENT_ONLY,*****#*****.com
I suggest copy pasting the data in excel to see how it fits. I tested it and seems like all the data goes correctly under their heading.

The solution for the case you provided is below. It is using JsonTextReader instead of LINQ to JSON to give you full control over output formatting. For example you did not specify how it should behave for arrays of string (otheruserState) so in my solution I separated string values with the dash. I'm using empty strings for null values.
string propertyName = "";
var isArray = false;
var arrayHeaderprinted = false;
var headers = new List<string>();
var data = new List<string>();
var arrayData = new List<string>();
using (var reader = new JsonTextReader(new StringReader(json)))
{
while (reader.Read())
{
switch (reader.TokenType)
{
case JsonToken.PropertyName:
propertyName = (string)reader.Value;
break;
case JsonToken.StartArray:
isArray = true;
break;
case JsonToken.EndArray:
case JsonToken.StartObject:
isArray = false;
if (arrayHeaderprinted)
{
arrayHeaderprinted = false;
data.Add(string.Join("-", arrayData));
}
break;
case JsonToken.Null:
case JsonToken.String:
case JsonToken.Boolean:
case JsonToken.Date:
case JsonToken.Float:
case JsonToken.Integer:
if (isArray)
{
if (!arrayHeaderprinted)
{
arrayHeaderprinted = true;
headers.Add(propertyName);
}
arrayData.Add(reader.Value.ToString());
}
else
{
headers.Add(propertyName);
data.Add(reader.Value?.ToString() ?? "");
}
break;
}
}
}
Console.WriteLine(string.Join(",", headers));
Console.WriteLine(string.Join(",", data));
The output it produces:
name,userStatusDate,lastAttestationDate,Id,lastName,suffix,gender,birthDate,ssn,ethnicity,languagesSpoken,personalEmail,otherNames,name,primaryuserState,otheruserState,practiceSetting,primaryEmail
Expired,04.04.2017 09:48:25,01.02.2019 09:50:42,13610875,************,,FEMALE,01.01.1970 01:01:00,000000000,INVALID_REFERENCE_VALUE,,,,APN,CO,CO-PP,INPATIENT_ONLY,*****#*****.com

Related

JSON deserialize throws exception

I have a C# code that defines a constant JSON string and a corresponding POCO class. however i get an exception:
The JSON value could not be converted Path: $ | LineNumber: 0 | BytePositionInLine: 1.
Code
try
{
var filters = JsonSerializer.Deserialize <CmsContactsFilter>(FilterJson);
}
catch(Exception ex)
{
}
JSON
#"[{""cms"":""us-its"",""group"":[""ciso"",""cloudAdminsDistributionList"",""cloudAdmins""]},""cms"":""us-csdaudit"",""abc"":[""biso"",""costManagement""]},]";
POCO Class
public class CmsContactsFilter
{
public string Cms { get; set; }
public List<string> Group { get; set; }
}
Your json is not valid, here is the valid version of your json:
[
{
"cms": "us-its",
"group": [
"ciso",
"cloudAdminsDistributionList",
"cloudAdmins"
]
},
{
"cms": "us-csdaudit",
"group": [
"biso",
"costManagement"
]
}
]
Your code should be looks like this:
using System.Text.Json;
string filterJson = System.IO.File.ReadAllText("data.json");
var filters = JsonSerializer.Deserialize<List<CmsContactsFilter>>(filterJson);
foreach (var item in filters)
{
Console.WriteLine(item.cms+":");
foreach (var y in item.group)
{
Console.WriteLine("----"+y);
}
}
public class CmsContactsFilter
{
public string cms { get; set; }
public List<string> group { get; set; }
}
the name of the properties of the the CmsContactsFilter should be same with your json attributes names. if they are in lower-case format, your attribute name in the C# should be in the lower-case too.
your json is not valid, you need to add { to the second array item, and use an object collection for deserialization
var FilterJson = #"[{""cms"":""us-its"",""group"":[""ciso"",""cloudAdminsDistributionList"",""cloudAdmins""]},{""cms"":""us-csdaudit"",""abc"":[""biso"",""costManagement""]}]";
var filters = System.Text.Json.JsonSerializer.Deserialize <List<CmsContactsFilter>>(FilterJson);
and fix class
public class CmsContactsFilter
{
public string cms { get; set; }
public List<string> group { get; set; }
public List<string> abc { get; set; }
}
but as I understand your array has much more objects then 2. So you can try this code for the big json with different array names (if you had used Newtonsoft.Json this code could be significanly simplier)
JsonArray array = JsonNode.Parse(FilterJson).AsArray();
List<CmsContactsFilter> filters = new List<CmsContactsFilter>();
foreach (JsonObject item in array)
{
var obj = new CmsContactsFilter();
foreach (var prom in item.AsObject())
{
var name = prom.Key;
if (name == "cms")
{
obj.cms = prom.Value.ToString();
continue;
}
obj.groupName = name;
obj.group = System.Text.Json.JsonSerializer.Deserialize<List<string>>(prom.Value.ToString());
}
filters.Add(obj);
}
}
class
public class CmsContactsFilter
{
public string cms { get; set; }
public string groupName { get; set; }
public List<string> group { get; set; }
}

Converting JSON array

I am attempting to use the Newtonsoft JSON library to parse a JSON string dynamically using C#. In the JSON is a named array. I would like to remove the square brackets from this array and then write out the modified JSON.
The JSON now looks like the following. I would like to remove the square bracket from the ProductDescription array.
{
"Product": "123",
"to_Description": [
{
"ProductDescription": "Product 1"
}
]
}
Desired result
{
"Product": "123",
"to_Description":
{
"ProductDescription": "Product 1"
}
}
I believe I can use the code below to parse the JSON. I just need some help with making the modification.
JObject o1 = JObject.Parse(File.ReadAllText(#"output.json"));
The to_Description property starts off as List<Dictionary<string,string>> and you want to take the first element from the List.
So, given 2 classes
public class Source
{
public string Product {get;set;}
public List<Dictionary<string,string>> To_Description{get;set;}
}
public class Destination
{
public string Product {get;set;}
public Dictionary<string,string> To_Description{get;set;}
}
You could do it like this:
var src = JsonConvert.DeserializeObject<Source>(jsonString);
var dest = new Destination
{
Product = src.Product,
To_Description = src.To_Description[0]
};
var newJson = JsonConvert.SerializeObject(dest);
Note: You might want to check there really is just 1 item in the list!
Live example: https://dotnetfiddle.net/vxqumd
You do not need to create classes for this task. You can modify your object like this:
// Load the JSON from a file into a JObject
JObject o1 = JObject.Parse(File.ReadAllText(#"output.json"));
// Get the desired property whose value is to be replaced
var prop = o1.Property("to_Description");
// Replace the property value with the first child JObject of the existing value
prop.Value = prop.Value.Children<JObject>().FirstOrDefault();
// write the changed JSON back to the original file
File.WriteAllText(#"output.json", o1.ToString());
Fiddle: https://dotnetfiddle.net/M83zv3
I have used json2csharp to convert the actual and desired output to classes and manipulated the input json.. this will help in the maintenance in future
First defined the model
public class ToDescription
{
public string ProductDescription { get; set; }
}
public class ActualObject
{
public string Product { get; set; }
public List<ToDescription> to_Description { get; set; }
}
public class ChangedObject
{
public string Product { get; set; }
public ToDescription to_Description { get; set; }
}
Inject the logic
static void Main(string[] args)
{
string json = "{\"Product\": \"123\", \"to_Description\": [ { \"ProductDescription\": \"Product 1\" } ]} ";
ActualObject actualObject = JsonConvert.DeserializeObject<ActualObject>(json);
ChangedObject changedObject = new ChangedObject();
changedObject.Product = actualObject.Product;
changedObject.to_Description = actualObject.to_Description[0];
string formattedjson = JsonConvert.SerializeObject(changedObject);
Console.WriteLine(formattedjson);
}
Why not:
public class EntityDescription
{
public string ProductDescription { get; set; }
}
public class Entity
{
public string Product { get; set; }
}
public class Source : Entity
{
[JsonProperty("to_Description")]
public EntityDescription[] Description { get; set; }
}
public class Target : Entity
{
[JsonProperty("to_Description")]
public EntityDescription Description { get; set; }
}
var raw = File.ReadAllText(#"output.json");
var source = JsonConvert.DeserializeObject<Source>(raw);
var target = new Target { Product = source.Product, Description = source.Description.FirstOrDefault() };
var rawResult = JsonConvert.SerializeObject(target);
Update For dynamic JSON
var jObject = JObject.Parse(File.ReadAllText(#"output.json"));
var newjObject = new JObject();
foreach(var jToken in jObject) {
if(jToken.Value is JArray) {
List<JToken> l = jToken.Value.ToObject<List<JToken>>();
if(l != null && l.Count > 0) {
newjObject.Add(jToken.Key, l.First());
}
} else {
newjObject.Add(jToken.Key, jToken.Value);
}
}
var newTxt = newjObject.ToString();

Reading JSON file with Array

I'm currently working on JSON string extraction using C#. My JSON string consist of an array with repetitive keys. Not sure if I'm describing it right since I'm new to this.
This is my JSON string
{"Index":
{ "LibraryName":"JGKing"
, "FormName":"AccountsPayable"
, "User":null
, "FilingPriority":null
, "FileDescription":null
, "Fields":
{"Field":
[
{ "Name":"invItemID"
, "Value":"6276"
}
,{ "Name":"invEntityCode"
, "Value":"16"
}
,{ "Name":"invVendorCode"
, "Value":"MIRUB01"
}
,{ "Name":"invNumber"
, "Value":"PWD5"
}
,{ "Name":"invDate"
, "Value":"2017-08-21"
}
,{ "Name":"invStatus"
, "Value":""
}
,{ "Name":"invCurrencyCode"
, "Value":"AU"
}
,{ "Name":"invCurrencyRate"
, "Value":"1"
}
,{ "Name":"invTax"
, "Value":"454.3"
}
, {"Name":"invTotal"
, "Value":"4997.27"
}
, {"Name":"invReceivedDate"
, "Value":"2017-09-06"
}
,{ "Name":"InvoiceLine1"
, "Value":"{\r\n \"invLineNumber\": \"1\",\r\n \"invPONumber\": \"\",\r\n \"invPOLineNo\": \"1\",\r\n \"invPOJobID\": \"\",\r\n \"invCostCode\": \"\",\r\n \"invCategory\": \"\",\r\n \"invGLCode\": \"61-01-49-6862.517\",\r\n \"invDescription\": \"\",\r\n \"invEntryType\": \"\",\r\n \"invAmount\": \"4542.97\",\r\n \"invTaxAmount\": \"454.3\",\r\n \"invTaxCode\": \"GST\",\r\n \"invAmountIncTax\": \"4997.27\"\r\n}"}]}}}
I need to extract the value of invItemID key which is inside the array.
I tried to serialize my json string from a class but it returns null in the List<>
Here's my code
public void CFExport(string jsonFile)
{
string ItemIDField;
string ItemIDValue;
using (StreamReader r = new StreamReader(jsonFile))
{
JsonSerializer s = new JsonSerializer();
var Idx = (JSONMain)s.Deserialize(r, typeof(JSONMain));
var flds = (Fields)s.Deserialize(r, typeof(Fields));
if (flds != null)
{
foreach (var _field in flds.Field)
{
ItemIDField = _field.Name;
ItemIDValue = _field.Value;
}
}
}
}
public class JSONMain
{
public Index Index { get; set; }
}
public class Index
{
public string LibraryName { get; set; }
public string FormName { get; set; }
public string User { get; set; }
public string FilingPriority { get; set; }
public string FileDescription { get; set; }
}
public class Fields
{
public List<Field> Field { get; set; }
}
public class Field
{
public string Name { get; set; }
public string Value { get; set; }
}
I hope you can help me.
Thanks in advance
Try to reflect the JSON file with your classes like this:
public class Index
{
public string LibraryName { get; set; }
public string FormName { get; set; }
public string User { get; set; }
public string FilingPriority { get; set; }
public string FileDescription { get; set; }
public Fields Fields { get; set; } //this line makes the difference
}
If you deserialize now, the fields should be populated automatically. I also advice you to use JsonConvert.Deserialze<>() since it is a bit easier (see documentation) and you are new to this topic.
Getting the value of invItemID could look like this:
public void CFExport(string jsonFile)
{
string ItemIDField = "invItemID";
string ItemIDValue;
using (StreamReader r = new StreamReader(jsonFile))
{
var Idx = JsonConvert.DeserializeObject<JSONMain>(r);
foreach(var field in Idx.Index.Fields.Field)
{
if(field.Name == ItemIDField)
{
ItemIDValue = field.Value;
}
}
}
}
Whoohoo. My first answer on Stackoverflow! I hope this helps you.
I need to extract the value of invItemID key which is inside the array.
You can retrieve value for your specified key invItemID from Field array by using JObject.
So you have no more need to manage classes for your json.
Here i created a console app for your demonstration purpose.
class Program
{
static void Main(string[] args)
{
//Get your json from file
string json = File.ReadAllText(#"Your path to json file");
//Parse your json
JObject jObject = JObject.Parse(json);
//Get your "Field" array to List of NameValuePair
var fieldArray = jObject["Index"]["Fields"]["Field"].ToObject<List<NameValuePair>>();
//Retrieve Value for key "invItemID"
string value = fieldArray.Where(x => x.Name == "invItemID").Select(x => x.Value).FirstOrDefault();
//Print this value on console
Console.WriteLine("Value: " + value);
Console.ReadLine();
}
}
class NameValuePair
{
public string Name { get; set; }
public string Value { get; set; }
}
Output:

Validate values in key value pair in a JSON

I need to validate a JSON against the available format. The sample JSON is as follows:
{
"sno": "1",
"project_name": "Abcd",
"contributors": [
{
"contributor_id": "1",
"contributor_name": "Ron"
},
{
"contributor_id": "2",
"contributor_name": "Dan"
}
],
"office": [ "Vegas", "New York" ]
}
In the above example, I need to validate the JSON as follows:
The value for sno must be a string.
The value for office must be a valid array.
The value for contrbutors must be a valid array with valid JSONs as members.
How can I parse the JSON and check if all the keys have valid values according to the above mentioned criteria?
You need object like this:
public class MyObject
{
public string sno { get; set; }
public string project_name { get; set; }
public List<Contrbutor> contrbutors { get; set; }
public List<string> office { get; set; }
}
public class Contrbutor
{
public string contributor_id { get; set; }
public string contributor_name { get; set; }
}
Pars it via JsonConvert
try
{
MyObject desObject = JsonConvert.DeserializeObject<MyObject>(yourJsonStringHere);
}
catch(Exception ex)
{
//IF PARSE IS NOT SUCCESSFUL CATCH THE PARSE EX HERE
}
and if Parse is successful than validate "desObject" values.
You can build your custom function to check the data type of value of respective key in your json.
1) Parse your json to JObject
2) Map this JObject to your SampleClass.
3) Then by using JTokenType you can validate if particular value of respective key is of type string or array or object.
public string ValidateJson(string json)
{
JObject jObject = JObject.Parse(json);
SampleClass model = jObject.ToObject<SampleClass>();
string response = string.Empty;
foreach (var i in model.data)
{
switch (i.Key)
{
case "sno":
if (i.Value.Type != JTokenType.String)
response = "SNo is not a string";
break;
case "project_name":
if (i.Value.Type != JTokenType.String)
response = "Project name is not a string";
break;
case "contributors":
if (i.Value.Type != JTokenType.Array)
response = "Contributors is not an array";
break;
case "office":
if (i.Value.Type != JTokenType.Array)
response = "Office is not an array";
break;
}
}
return response;
}
Your SampleClass would be
class SampleClass
{
[JsonExtensionData]
public Dictionary<string, JToken> data { get; set; }
}

Parse JSON Array With C#

I am querying an API and returning data to a C# Console App. I am able to query my data successfully except for the array element of such. This is how the data is returned in JSON format
[
{
"UserType": "Admin",
"UserPerms:" [
{
"level1:" "Yes",
"level2:" "No",
"level3:" "No",
"level4:" "Yes",
"level5:" [
{
"door1:" "Yes",
"door2:" "No",
"door3:" "No",
"doory4:" "Yes"
}
]
}
]
}
]
And this is the C# syntax that I am trying to use to return the data - what is the proper C# syntax to return each door value for level5?
public class RootObject
{
public string UserType { get; set; }
public List<UserPerms> UserPerms { get; set; }
}
public class UserPerms
{
public string level1 { get; set; }
public string level2 { get; set; }
public string level3 { get; set; }
public string level4 { get; set; }
public string[] level5 { get; set; }
}
public class Main[]
{
var response = syncClient.DownloadString(url);
var o = JsonConvert.DeserializeObject<RootObject[]>(response);
foreach (RootObject ro in o)
if (ro.UserPerms != null)
foreach (UserPerms info in ro.UserPerms)
{
Console.WriteLine("Access to Level1" + info.level1);
Console.WriteLine("Access to Level2" + info.level2);
Console.WriteLine("Access to Level3" + info.level3);
Console.WriteLine("Access to Level4" + info.level4);
Console.WriteLine("Access to Level5" + info.level5);
}
}
The JSON for level5 displays a "list" of "key-value pair", so....
public List<Dictionary<string, string>> level5 { get; set; }
I'll try to come up with a fiddle soon.

Categories