how to work with nested json object in c# - c#

api return json which is nested and i dont know to retrieve data from it and map it to my model. i want to retrieve the data from nested but not sure how to do this with index and value. Thanks in Advance.
public class MikesExcelModel
{
//public int id;
//public object AuthorizingManagerId;
public string Name;
//public DateTime UpdateDate;
public string Phone;
public string Email;
}
public class MikesExcelResults
{
public List<MikesExcelModel> value = new List<MikesExcelModel>();
}
public List<MikesExcelModel> GetExcel()
{
using (HttpClient client = new HttpClient())
{
addToken(client);
var result = client.GetAsync("https://graph.microsoft.com/beta/sites/ucfdev.sharepoint.com,4c319763-130d-4ee1-bc1f-72543da0a847,8a2f59f4-9d56-4aec-be21-33d0347293d1/drives/b!Y5cxTA0T4U68H3JUPaCoR_RZL4pWnexKviEz0DRyk9HjXtfo70gjRbH706GdwO5m/items/01HA4SXKSESD3RW3UYPNCZ2OHQAEWWDTKH/workbook/worksheets('sheet1')/tables(%27%7B079215E2-A6D7-4CC2-AB1E-9AC38F36D1CC%7D%27)/rows").Result;
if (result.IsSuccessStatusCode)
{
var responseContent = result.Content;
// by calling .Result you are synchronously reading the result
string responseString = responseContent.ReadAsStringAsync().Result;
JavaScriptSerializer serialiser = new JavaScriptSerializer();
// dynamic apiResult = serialiser.DeserializeObject(responseString);
return Utilities.DeserializeObject<MikesExcelResults>(result.Content.ReadAsStringAsync().Result).value;
}
else
throw new Exception("Couldn't get excel datas.");
}
}
}
Data return by api looks like this:
{
"#odata.context": "https://graph.microsoft.com/beta/$metadata#sites('ucfdev.sharepoint.com%2C4c319763-130d-4ee1-bc1f-72543da0a847%2C8a2f59f4-9d56-4aec-be21-33d0347293d1')/drives('b%21Y5cxTA0T4U68H3JUPaCoR_RZL4pWnexKviEz0DRyk9HjXtfo70gjRbH706GdwO5m')/items('01HA4SXKSESD3RW3UYPNCZ2OHQAEWWDTKH')/workbook/worksheets('sheet1')/tables('%7B079215E2-A6D7-4CC2-AB1E-9AC38F36D1CC%7D')/rows",
"value": [
{
"#odata.id": "/sites('ucfdev.sharepoint.com%2C4c319763-130d-4ee1-bc1f-72543da0a847%2C8a2f59f4-9d56-4aec-be21-33d0347293d1')/drives('b%21Y5cxTA0T4U68H3JUPaCoR_RZL4pWnexKviEz0DRyk9HjXtfo70gjRbH706GdwO5m')/items('01HA4SXKSESD3RW3UYPNCZ2OHQAEWWDTKH')/workbook/worksheets(%27%7B00000000-0001-0000-0000-000000000000%7D%27)/tables(%27%7B079215E2-A6D7-4CC2-AB1E-9AC38F36D1CC%7D%27)/rows/itemAt(index=0)",
"index": 0,
"values": [
[
"Mike Callahan",
"407-266-1431",
"MTC#ucf.edu"
]
]
},
{
"#odata.id": "/sites('ucfdev.sharepoint.com%2C4c319763-130d-4ee1-bc1f-72543da0a847%2C8a2f59f4-9d56-4aec-be21-33d0347293d1')/drives('b%21Y5cxTA0T4U68H3JUPaCoR_RZL4pWnexKviEz0DRyk9HjXtfo70gjRbH706GdwO5m')/items('01HA4SXKSESD3RW3UYPNCZ2OHQAEWWDTKH')/workbook/worksheets(%27%7B00000000-0001-0000-0000-000000000000%7D%27)/tables(%27%7B079215E2-A6D7-4CC2-AB1E-9AC38F36D1CC%7D%27)/rows/itemAt(index=1)",
"index": 1,
"values": [
[
"Michael Callahan",
"407-823-3455",
"mtcallah#ucf.edu"
]
]
},
{
"#odata.id": "/sites('ucfdev.sharepoint.com%2C4c319763-130d-4ee1-bc1f-72543da0a847%2C8a2f59f4-9d56-4aec-be21-33d0347293d1')/drives('b%21Y5cxTA0T4U68H3JUPaCoR_RZL4pWnexKviEz0DRyk9HjXtfo70gjRbH706GdwO5m')/items('01HA4SXKSESD3RW3UYPNCZ2OHQAEWWDTKH')/workbook/worksheets(%27%7B00000000-0001-0000-0000-000000000000%7D%27)/tables(%27%7B079215E2-A6D7-4CC2-AB1E-9AC38F36D1CC%7D%27)/rows/itemAt(index=2)",
"index": 2,
"values": [
[
"cvcfcv",
"zVCCvc",
"cvvvvb"
]
]
}
]
}

Maybe traditional way to extract JSON data with Newtonsoft.Json library.
Convert jsonData to JObject (via JObject.Parse).
Get first-level value.
Get second-level values.
Flatten second-level values.
From
[[["Mike Callahan", "407-266-1431", "MTC#ucf.edu"], ...]]
To
[["Mike Callahan", "407-266-1431", "MTC#ucf.edu"], ...]
Convert flattenChildrenValues to List<MikesExcelModel>.
Add List<MikesExcelModel> to results.value
using System;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Linq;
var jsonData = #"{
""#odata.context"": ""https://graph.microsoft.com/beta/$metadata#sites('ucfdev.sharepoint.com%2C4c319763-130d-4ee1-bc1f-72543da0a847%2C8a2f59f4-9d56-4aec-be21-33d0347293d1')/drives('b%21Y5cxTA0T4U68H3JUPaCoR_RZL4pWnexKviEz0DRyk9HjXtfo70gjRbH706GdwO5m')/items('01HA4SXKSESD3RW3UYPNCZ2OHQAEWWDTKH')/workbook/worksheets('sheet1')/tables('%7B079215E2-A6D7-4CC2-AB1E-9AC38F36D1CC%7D')/rows"",
""value"": [
{
""#odata.id"": ""/sites('ucfdev.sharepoint.com%2C4c319763-130d-4ee1-bc1f-72543da0a847%2C8a2f59f4-9d56-4aec-be21-33d0347293d1')/drives('b%21Y5cxTA0T4U68H3JUPaCoR_RZL4pWnexKviEz0DRyk9HjXtfo70gjRbH706GdwO5m')/items('01HA4SXKSESD3RW3UYPNCZ2OHQAEWWDTKH')/workbook/worksheets(%27%7B00000000-0001-0000-0000-000000000000%7D%27)/tables(%27%7B079215E2-A6D7-4CC2-AB1E-9AC38F36D1CC%7D%27)/rows/itemAt(index=0)"",
""index"": 0,
""values"": [
[
""Mike Callahan"",
""407-266-1431"",
""MTC#ucf.edu""
]
]
},
{
""#odata.id"": ""/sites('ucfdev.sharepoint.com%2C4c319763-130d-4ee1-bc1f-72543da0a847%2C8a2f59f4-9d56-4aec-be21-33d0347293d1')/drives('b%21Y5cxTA0T4U68H3JUPaCoR_RZL4pWnexKviEz0DRyk9HjXtfo70gjRbH706GdwO5m')/items('01HA4SXKSESD3RW3UYPNCZ2OHQAEWWDTKH')/workbook/worksheets(%27%7B00000000-0001-0000-0000-000000000000%7D%27)/tables(%27%7B079215E2-A6D7-4CC2-AB1E-9AC38F36D1CC%7D%27)/rows/itemAt(index=1)"",
""index"": 1,
""values"": [
[
""Michael Callahan"",
""407-823-3455"",
""mtcallah#ucf.edu""
]
]
},
{
""#odata.id"": ""/sites('ucfdev.sharepoint.com%2C4c319763-130d-4ee1-bc1f-72543da0a847%2C8a2f59f4-9d56-4aec-be21-33d0347293d1')/drives('b%21Y5cxTA0T4U68H3JUPaCoR_RZL4pWnexKviEz0DRyk9HjXtfo70gjRbH706GdwO5m')/items('01HA4SXKSESD3RW3UYPNCZ2OHQAEWWDTKH')/workbook/worksheets(%27%7B00000000-0001-0000-0000-000000000000%7D%27)/tables(%27%7B079215E2-A6D7-4CC2-AB1E-9AC38F36D1CC%7D%27)/rows/itemAt(index=2)"",
""index"": 2,
""values"": [
[
""cvcfcv"",
""zVCCvc"",
""cvvvvb""
]
]
}
]
}";
var jsonObj = JObject.Parse(jsonData);
// Get first-level value
JArray jsonValue = jsonObj["value"] as JArray;
// Get second-level values
var childrenValues = jsonValue.Children<JObject>()["values"];
// Flatten second-level values
var flattenChildrenValues = childrenValues.Values<JArray>() as IEnumerable<JArray>;
// Read flattenChildrenValues to List<MikesExcelModel>
List<MikesExcelModel> excelModels = flattenChildrenValues
.Select(x => new MikesExcelModel
{
Name = x[0].ToString(),
Phone = x[1].ToString(),
Email = x[2].ToString()
})
.ToList();
// Add List<MikesExcelModel> to results.value
MikesExcelResults results = new MikesExcelResults();
results.value.AddRange(excelModels);
foreach (var model in results.value)
{
Console.WriteLine(String.Format("Name: {0}, Phone: {1}, Email: {2}", model.Name, model.Phone, model.Email));
}
Sample program

Related

C# Directory path to json formatting

I'm trying to save a folder path in a json file but I can't seem to find/figure out how to get it to parse it correctly
I'm using the following code to write the json file
string location = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string userDataPreset = #"{UserData: [{Language: ""NL"", location: " + location + "}]}";
File.WriteAllText(userData, userDataPreset);
This creates the following json:
{
"UserData": [
{
"Language": "NL",
"location": C:\Users\stage\OneDrive\Documenten
}
]
}
But I need it to become the following, with the double // and "":
{
"UserData": [
{
"Language": "NL",
"location": "C:\\Users\\stage\\OneDrive\\Documenten"
}
]
}
What am I missing to parse this path correctly?
to fix the string you can use an Escape method
location=Regex.Escape(location);
but the most relable method is to create an anonymous object and serialize it
var data = new { UserData = new[] { new { Language = "NL", Location = location } } };
var json = System.Text.Json.JsonSerializer.Serialize(data, new JsonSerializerOptions { WriteIndented = true});
File.WriteAllText(userData, json);
json
{
"UserData": [
{
"Language": "NL",
"Location": "C:\\Users\\stage\\OneDrive\\Documenten"
}
]
}

how to replace property values in a dynamic JSON?

I'm reading my json file from and trying to replace the property values. JSON file is below.
{
"fields": {
"summary": "summaryValue",
"project": {
"key": "projectValue"
},
"priority": {
"name": "priorityValue"
},
"Requestor": {
"name": "RequestorValue"
},
"issue": {
"name": "issueValue"
},
"labels": "LabelValue",
"customfield_xyz": "customfield_xyzValue"
}
}
How can I replace the value for each item inside the fields property ?
for ex:
{"fields": {
"summary": "NewsummaryValue",
"project": {
"key": "NewprojectValue"
},
"priority": {
"name": "NewpriorityValue"
}
}
}
Below is the code to parse my json file,
StreamReader r = new StreamReader(filepath);
var jsondata = r.ReadToEnd();
var jobj = JObject.Parse(jsondata);
foreach (var item in jobj.Properties())
{
\\replace code
}
I do not know exactly what you want. But I changed the json information in the code snippet as you wanted.
dynamic dataCollection = JsonConvert.DeserializeObject<dynamic>(jsonData);
string summary = dataCollection["fields"]["summary"];
string project = dataCollection["fields"]["project"]["key"];
string priority = dataCollection["fields"]["priority"]["name"];
dynamic json = new JObject();
json.summary = summary;
json.project = project;
json.priority = priority;
dynamic jsonRoot = new JObject();
jsonRoot.fields = json;
Console.WriteLine(jsonRoot.ToString());
output:

Add new record in json

I want to add a new record to the json collection:
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"id": 1,
"name": "Location1",
"geometry": {
"type": "Point",
"coordinates": [
150.74379,
-30.280119
]
}
},
{
"type": "Feature",
"id": 2,
"name": "Location2",
"geometry": {
"type": "Point",
"coordinates": [
148.387392,
-23.781484
]
}
}]
}
and I want to find what is the best way to create such an object and to insert it. So far I added the code below, which raises an error
Can not add Newtonsoft.Json.Linq.JObject to Newtonsoft.Json.Linq.JObject.
when I want to add the new object to the array
var array = JsonConvert.DeserializeObject<dynamic>(json);
dynamic jsonObject = new JObject(); // needs using Newtonsoft.Json.Linq;
jsonObject.type = "feature";
jsonObject.id = 3;
jsonObject.name = sAddress;
jsonObject.type = "Point";
jsonObject.coordinates = "12, 13";
array.Add(jsonObject); // error Can not add Newtonsoft.Json.Linq.JObject to Newtonsoft.Json.Linq.JObject.
The variable you call array is not an array based on the json above. The array is in the features property. You would have to do array.features.Add(jsonObject); to get your above code to work.
Like
var rootObject = JsonConvert.DeserializeObject<dynamic>(json);
dynamic feature = new JObject();
feature.type = "Feature";
feature.id = 3;
feature.name = sAddress;
dynamic geometry = new JObject();
geometry.type = "Point";
geometry.coordinates = new JArray(12, 13);
feature.geometry = geometry;
rootObject.features.Add(feature);

Json Searching Data Structures

This is my Data Structure and I'm trying to access it with simpleJason, through unity/c#, I have accidentally gotten the right data here and there, and otherwise gotten completely empty arrays, I'd like to know if my JSON file is improperly setup for my data structure, or if the parser is somehow falling though, or not properly matching what I'm looking for.
JSON File:
{
"categories": [
{
"name" : "entertainment",
"projects": [
{
"name": "Awards",
"description": "Awards Shows",
"credits": [
"Lead Engineer - Dave Jones",
"VFX Supervisor - John Adrian",
"CG Supervisor - Evan Klein"
],
"meta": [
"awards",
"show",
"stars",
"red carpet"
],
"assets": [
{
"name": "Screen Actors Guild Awards",
"filename": "SAG_Awards.mp4",
"icon": "sag.png",
"stereo": false,
"meta": [
"Screen",
"Actors",
"Guild"
]
},
{
"name": "No Awards",
"filename": "No_SAG_Awards.mp4",
"icon": "no_sag.png",
"stereo": false,
"meta": [
"Screen",
"Actors",
"Guild"
]
},
{
"name": "None Awds",
"filename": "None_SAG_Awards.mp4",
"icon": "none_sag.png",
"stereo": false,
"meta": [
"Screen",
"Actors",
"Guild"
]
}
]
}
]
}
]
}
This is the struct :
private struct jsonAsset {
public string category;
public string project;
public string description;
public string[] credits;
public string[] meta;
public string asset;
public FileInfo file;
public FileInfo icon;
public bool stereo;
public bool overUnder;
};
This is the function:
jsonAsset LoadSceneDataFromJSON(FileInfo jsonFile)
{
jsonAsset asset = new jsonAsset();
Debug.Log("Processing : " + jsonFile);
// Parse File for Data
var N = JSON.Parse(File.ReadAllText(jsonFile.FullName));
var cat_arr = N["categories"].AsArray;
asset.category = N["categories"]["name"].Value;
Debug.Log(N["categories"]["projects"]["assets"]["filename"].Value);
foreach (JSONNode n in cat_arr)
{
asset.project = n["name"].Value;
// Credits
var proj_credits = n["credits"].AsArray;
foreach (JSONNode pc in proj_credits)
{
asset.credits[asset.credits.Length] = pc["credits"].Value;
}
// Project Meta
var proj_meta = n["meta"].AsArray;
foreach (JSONNode pm in proj_meta)
{
asset.meta[asset.meta.Length] = pm["meta"].Value;
}
// Project Array
var proj_arr = n["projects"].AsArray;
foreach (JSONNode nn in proj_arr)
{
var asset_arr = nn["assets"].AsArray;
asset.asset = nn["assets"]["name"].Value;
foreach (JSONNode nnn in asset_arr)
{
asset.asset = nnn["name"].Value;
asset.file = new FileInfo(m_dir + nnn["filename"].Value);
asset.icon = new FileInfo(m_dir + nnn["icon"].Value);
var asset_meta = nnn["meta"].AsArray;
foreach (JSONNode am in asset_meta)
{
asset.meta[asset.meta.Length] = am.Value;
}
}
}
}
return asset;
}
You are treating projects as an object instead of an array.
I dont know what JSON library you are using to give you guidance, but something like this will probably work:
N["categories"]["projects"][0]["assets"]["filename"].Value

C# MongoDb - Output id field properly?

I don't understand how can I output id properly when displaying objects. It's either ObjectId() that I can't parse back to object or some object that has id in it that I can parse but it looks weird.
Note that mapping it to class is not an option, it needs to be fully dynamic because different users have different fields.
Code
public List<object> Get()
{
var client = new MongoClient("mongodb://localhost");
var server = client.GetServer();
var database = server.GetDatabase("api_test");
var collection = database.GetCollection("users");
var json = collection.FindAllAs<BsonDocument>().ToJson(new JsonWriterSettings { OutputMode = JsonOutputMode.Strict });
var obj = JsonConvert.DeserializeObject<List<object>>(json);
return obj;
}
Example
[
{
"_id": {
"$oid": "528e7f9bb1fece903aa9b246"
},
"Name": "Steve",
"Age": 60
},
{
"_id": {
"$oid": "528e7fabb1fece903aa9b247"
},
"Name": "Alice",
"Age": 44
}
]
What I would like
[
{
"_id": "528e7f9bb1fece903aa9b246",
"Name": "Steve",
"Age": 60
},
{
"_id": "528e7fabb1fece903aa9b247",
"Name": "Alice",
"Age": 44
}
]
You can do this by explicitly updating your query result to convert _id to a string before it's serialized to JSON:
var docs = test.FindAll().ToList();
foreach (var doc in docs)
{
doc["_id"] = doc["_id"].ToString();
}
var json = docs.ToJson(
new JsonWriterSettings { OutputMode = JsonOutputMode.Strict });

Categories