I need to convert a json to csv. The problem is that I can't select everything that i need in the nested json structure. Example of the json file:
{
"system": {
"created": "2021-08-01T13:33:37.123Z",
"by": "web"
},
"location": {
"id": 100,
"country": "DE"
},
"order": [
{
"OrderID": 22,
"OrderName": "Soda",
"OrderArticles": [
{
"Size": 33,
"ProductName": "Coke",
"ProductId": "999"
},
{
"Size": 66,
"ProductName": "Fanta",
"ProductId": "888"
},
{
"Size": 50,
"ProductName": "Pepsi",
"ProductId": "444"
}
],
"ProcessedId": 1001,
"Date": "2021-08-02"
},
{
"OrderID": 23,
"OrderName": "Beverage",
"OrderArticles": [
{
"Size": 44,
"ProductName": "Coke",
"ProductId": "999"
}
],
"ProcessedId": 1002,
"Date": "2021-08-03"
}
]
}
This is the output i want:
created;by;id;country;OrderID;OrderName;Size;ProductName;ProductId
2021-08-01T13:33:37.123Z;web;100;DE;22;Soda;33;Coke;999
2021-08-01T13:33:37.123Z;web;100;DE;22;Soda;66;Fanta;888
2021-08-01T13:33:37.123Z;web;100;DE;22;Soda;50;Pepsi;444
2021-08-01T13:33:37.123Z;web;100;DE;23;Beverage;44;Coke;999
I can get the created and by values by them self and the values for OrderArticles. I just can't figure out how to get them togheter. This is the code I have used to get the result but divide into 2 different results:
using (var r = new ChoJSONReader(inBlob).WithJSONPath("$..order[*]").AllowComplexJSONPath(true))
{
return (r.SelectMany(r1 => ((dynamic[])r1.OutputArticles).Select(r2 => new
{
r1.OrderID,
r1.OrderName,
r1.Size,
r1.ProductName,
r1.ProductId
})));
}
using (var r = new ChoJSONReader(inBlob).WithJSONPath("$").AllowComplexJSONPath(true))
{
return (r.Select(r1 => new
{
r1.system.created,
r1.system.by
}));
}
Since you need system.created, system.by, location.id, location.country fields, you must load the entire json from root and then compose the expected object for the csv
Here are the working samples (Take the latest nuget packages)
METHOD 1: (Using dynamic model)
StringBuilder csv = new StringBuilder();
using (var r = new ChoJSONReader("*** YOUR JSON FILE PATH ***")
.JsonSerializationSettings(s => s.DateParseHandling = DateParseHandling.None)
)
{
using (var w = new ChoCSVWriter(csv)
.WithDelimiter(";")
.WithFirstLineHeader())
{
w.Write(r.SelectMany(root =>
((Array)root.order).Cast<dynamic>()
.SelectMany(order => ((Array)order.OrderArticles).Cast<dynamic>()
.Select(orderarticle => new
{
root.system.created,
root.system.by,
root.location.id,
order.OrderID,
order.OrderName,
orderarticle.Size,
orderarticle.ProductName,
orderarticle.ProductId,
})
)
)
);
}
}
Console.WriteLine(csv.ToString());
Output:
created;by;id;OrderID;OrderName;Size;ProductName;ProductId
2021-08-01T01:33:37.123Z;web;100;22;Soda;33;Coke;999
2021-08-01T01:33:37.123Z;web;100;22;Soda;66;Fanta;888
2021-08-01T01:33:37.123Z;web;100;22;Soda;50;Pepsi;444
2021-08-01T01:33:37.123Z;web;100;23;Beverage;44;Coke;999
METHOD 2: Using POCO model
Define POCO objects matching with input JSON
public class System
{
[JsonProperty("created")]
public string Created { get; set; }
[JsonProperty("by")]
public string By { get; set; }
}
public class Location
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("country")]
public string Country { get; set; }
}
public class OrderArticle
{
[JsonProperty("Size")]
public int Size { get; set; }
[JsonProperty("ProductName")]
public string ProductName { get; set; }
[JsonProperty("ProductId")]
public string ProductId { get; set; }
}
public class Order
{
[JsonProperty("OrderID")]
public int OrderID { get; set; }
[JsonProperty("OrderName")]
public string OrderName { get; set; }
[JsonProperty("OrderArticles")]
public List<OrderArticle> OrderArticles { get; set; }
[JsonProperty("ProcessedId")]
public int ProcessedId { get; set; }
[JsonProperty("Date")]
public string Date { get; set; }
}
public class OrderRoot
{
[JsonProperty("system")]
public System System { get; set; }
[JsonProperty("location")]
public Location Location { get; set; }
[JsonProperty("order")]
public List<Order> Orders { get; set; }
}
Then use the code below to load the json and output CSV in expected format
StringBuilder csv = new StringBuilder();
using (var r = new ChoJSONReader<OrderRoot>("*** YOUR JSON FILE PATH ***")
.UseJsonSerialization()
)
{
using (var w = new ChoCSVWriter(csv)
.WithDelimiter(";")
.WithFirstLineHeader())
{
w.Write(r.SelectMany(root =>
root.Orders
.SelectMany(order => order.OrderArticles
.Select(orderarticle => new
{
created = root.System.Created,
by = root.System.By,
id = root.Location.Id,
order.OrderID,
order.OrderName,
orderarticle.Size,
orderarticle.ProductName,
orderarticle.ProductId,
})
)
)
);
}
}
Console.WriteLine(csv.ToString());
METHOD 3: Simplified dynamic model approach
StringBuilder csv = new StringBuilder();
using (var r = new ChoJSONReader("*** YOUR JSON FILE PATH ***")
.WithField("created", jsonPath: "$..system.created", isArray: false, valueConverter: o => ((DateTime)o).ToString("yyyy-MM-ddThh:mm:ss.fffZ"))
.WithField("by", jsonPath: "$..system.by", isArray: false)
.WithField("id", jsonPath: "$..location.id", isArray: false)
.WithField("country", jsonPath: "$..location.country", isArray: false)
.WithField("OrderID")
.WithField("OrderName")
.WithField("Size")
.WithField("ProductName")
.WithField("ProductId")
.Configure(c => c.FlattenNode = true)
)
{
using (var w = new ChoCSVWriter(csv)
.WithDelimiter(";")
.WithFirstLineHeader())
{
w.Write(r);
}
}
Console.WriteLine(csv.ToString());
METHOD 4: Even far simplified dynamic model approach
StringBuilder csv = new StringBuilder();
using (var r = new ChoJSONReader("*** YOUR JSON FILE PATH ***")
.Configure(c => c.FlattenNode = true)
.JsonSerializationSettings(s => s.DateParseHandling = DateParseHandling.None)
)
{
using (var w = new ChoCSVWriter(csv)
.WithDelimiter(";")
.WithFirstLineHeader()
.Configure(c => c.IgnoreDictionaryFieldPrefix = true)
)
{
w.Write(r);
}
}
Console.WriteLine(csv.ToString());
Sample fiddle: https://dotnetfiddle.net/VCezp8
Here is my solution.
This is my data model:
using System.Text.Json.Serialization;
namespace JsonToCSV.Models;
// Root myDeserializedClass = JsonSerializer.Deserialize<Root>(myJsonResponse);
public class System
{
[JsonPropertyName("created")]
public string Created { get; set; }
[JsonPropertyName("by")]
public string By { get; set; }
}
public class Location
{
[JsonPropertyName("id")]
public int Id { get; set; }
[JsonPropertyName("country")]
public string Country { get; set; }
}
public class OrderArticle
{
[JsonPropertyName("Size")]
public int Size { get; set; }
[JsonPropertyName("ProductName")]
public string ProductName { get; set; }
[JsonPropertyName("ProductId")]
public string ProductId { get; set; }
}
public class Order
{
[JsonPropertyName("OrderID")]
public int OrderID { get; set; }
[JsonPropertyName("OrderName")]
public string OrderName { get; set; }
[JsonPropertyName("OrderArticles")]
public List<OrderArticle> OrderArticles { get; set; }
[JsonPropertyName("ProcessedId")]
public int ProcessedId { get; set; }
[JsonPropertyName("Date")]
public string Date { get; set; }
}
public class Root
{
[JsonPropertyName("system")]
public System System { get; set; }
[JsonPropertyName("location")]
public Location Location { get; set; }
[JsonPropertyName("order")]
public List<Order> Orders { get; set; }
}
and here is business logic (if you want, I can replace it with LINQ):
using System.Text.Json;
using JsonToCSV.Models;
var dataAsText = File.ReadAllText("data.json");
var data = JsonSerializer.Deserialize<Root>(dataAsText);
var csv = new List<string> { "created;by;id;country;OrderID;OrderName;Size;ProductName;ProductId" };
foreach (var order in data.Orders)
{
foreach (var orderArticle in order.OrderArticles)
{
csv.Add(String.Format("{0};{1};{2};{3};{4};{5};{6};{7};{8}",
data.System.Created,
data.System.By,
data.Location.Id,
data.Location.Country,
order.OrderID,
order.OrderName,
orderArticle.Size,
orderArticle.ProductName,
orderArticle.ProductId
));
}
}
File.WriteAllLines("data.csv", csv);
Creates .csv file with content:
created;by;id;country;OrderID;OrderName;Size;ProductName;ProductId
2021-08-01T13:33:37.123Z;web;100;DE;22;Soda;33;Coke;999
2021-08-01T13:33:37.123Z;web;100;DE;22;Soda;66;Fanta;888
2021-08-01T13:33:37.123Z;web;100;DE;22;Soda;50;Pepsi;444
2021-08-01T13:33:37.123Z;web;100;DE;23;Beverage;44;Coke;999
Related
Please refer to the JSON below : -
{
"operations": [
{
"creationTime": "2022-06-02T10:28:28.765+03:00",
"deviceId": "43432103",
"deviceName": "P25-SC-0228",
"id": "121985460",
"status": "PENDING",
"com_cumulocity_model": {
"op": "s",
"param": "waterStartDateTime",
"value": "1/2/2018, 7:30:00 AM"
},
"description": "Generate Plan"
},
{
"creationTime": "2022-06-02T10:28:36.276+03:00",
"deviceId": "43432103",
"deviceName": "P25-SC-0228",
"id": "121985465",
"status": "PENDING",
"com_cumulocity_model": {
"Mode": 0,
"StopStationPayload": "[{\"ControllerAddress\":11,\"StationAddress\":26}]"
},
"description": "Stop Station"
}
],
"statistics": {
"currentPage": 1,
"pageSize": 5
}
}
Please find my code below : -
namespace handleDeviceOperations
{
class Program
{
string operationID = String.Empty;
static async Task Main(string[] args)
{
var serviceCollection = new ServiceCollection();
ConfigureServices(serviceCollection);
var services = serviceCollection.BuildServiceProvider();
var httpClientFactory = services.GetRequiredService<IHttpClientFactory>();
var httpClientGetOperations = httpClientFactory.CreateClient("getOperations");
var request1 = await httpClientGetOperations.GetAsync("");
if (request1.IsSuccessStatusCode)
{
var responseMessage1 = await request1.Content.ReadAsStringAsync();
JObject obj = JObject.Parse(responseMessage1);
var root = JsonConvert.DeserializeObject<RootObject>(responseMessage1);
RootObject myDeserializedObject = JsonConvert.DeserializeObject<RootObject>(responseMessage1);
if (obj["operations"].HasValues)
{
foreach(var item in myDeserializedObject.operations)
{
switch(item.description)
{
case "Generate Plan":
var gen_plan=JObject.Parse(responseMessage1)["operations"];
string[] gen_plan_list_operationID =gen_plan.Select(o => (string) o["id"]).ToArray();
JObject[] gen_plan_list_payload = gen_plan.Select(o => (JObject) o["com_cumulocity_model"]).ToArray();
break;
case "Stop Station":
var stop_st=JObject.Parse(responseMessage1)["operations"];
string[] stop_st_list_operationID =stop_st.Select(o => (string) o["id"]).ToArray();
JObject[] stop_st_list_payload = stop_st.Select(o => (JObject) o["com_cumulocity_model"]).ToArray();
var httpClientStopStation = httpClientFactory.CreateClient("executeOperations");
var request4 = await httpClientStopStation.PostAsync("");
break;
}
}
}
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddHttpClient("getOperations", options =>
{
options.BaseAddress = new Uri("https://myurl.com?deviceId=43432103");
options.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic","auth value");
});
services.AddHttpClient("executeOperations", options =>
{
options.BaseAddress = new Uri("https://myurl.com/"+operationID);
options.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic","auth value");
options.DefaultRequestHeaders.Add("Accept", "application/vnd.com.nsn.xyz.operation+json");
});
}
public class RootObject
{
public List<operation> operations { get; set; }
}
public class operation
{
public golfController com_cumulocity_model { get; set; }
public string description {get; set;}
}
public class golfController
{
public int mode { get; set; }
public string StopStationPayload { get; set; }
}
}
}
Question #1
In the switch case I want to fetch the value of com_cumulocity_model and id which belongs to the same JSON Object where case(value_of_description) is satisfied.
For example :
If case "Stop Station": is satisfied, I want to fetch the equivalent value of com_cumulocity_model and id inside it i.e. {"Mode": 0,"StopStationPayload": "[{\"ControllerAddress\":11,\"StationAddress\":26}]"} and "121985465" respectively. It must be compared to the value inside case and fetched on based of that.
Question #2
How do we add this value of id = "121985465" which we discussed above to the end of th url for making PostAsync request inside case("Stop Station") in lines var httpClientStopStation = httpClientFactory.CreateClient("executeOperations"); var request4 = await httpClientStopStation.PostAsync("");?
Short way. If you need just com_cumulocity_model
var operations = JObject.Parse(json)["operations"];
var com_cumulocity_model = operations.Where(o => (string) o["description"] == "Stop Station")
.Select(o => o["com_cumulocity_model"])
.FirstOrDefault();
Console.WriteLine(com_cumulocity_model.ToString());
result
{
"Mode": 0,
"StopStationPayload": "[{\"ControllerAddress\":11,\"StationAddress\":26}]"
}
But if you need the whole data you can use this code for deserializing json.
var data = JsonConvert.DeserializeObject<Data>(json);
classes
public class Data
{
public List<Operation> operations { get; set; }
public Statistics statistics { get; set; }
}
public class Operation
{
public DateTime creationTime { get; set; }
public string deviceId { get; set; }
public string deviceName { get; set; }
public string status { get; set; }
public ComCumulocityModel com_cumulocity_model { get; set; }
public string description { get; set; }
}
public class ComCumulocityModel
{
public string op { get; set; }
public string param { get; set; }
public string value { get; set; }
public int? Mode { get; set; }
public string StopStationPayload { get; set; }
}
public class Statistics
{
public int currentPage { get; set; }
public int pageSize { get; set; }
}
you can just remove Statistics class and statitics property from Data if you dont need it. The same about another properties
Now you can use Linq to get any data, for example
ComCumulocityModel com_cumulocity_model = data.operations
.Where(o => o.description == "Stop Station")
.Select(o => o.com_cumulocity_model)
.FirstOrDefault();
result (in json format)
{
"Mode": 0,
"StopStationPayload": "[{\"ControllerAddress\":11,\"StationAddress\":26}]"
}
how to print
var jsonSettings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
Formatting=Newtonsoft.Json.Formatting.Indented
};
Console.WriteLine(JsonConvert.SerializeObject( com_cumulocity_model, jsonSettings));
I have json format as below. In that I have multiple records coming, check below json.
{
"metadata":{
"TotalCount":11,
"CurrentPageNumber":1,
},
"records":[
{
"offerId":"e1b75d86-67b1-4557-a381-5474383da3fb",
"isContract":true,
"transportRouteId":"e1b75d86-67b1-4557-a381-5474383da3fb",
"transportOrderId":"SEZYMY-210720-010097",
"schedule":null,
},
]
}
Now I want to add new value in each this records array, so how can I do that.
I want to add this value : ("carrierExpiredDate", (carrierExpiredDate.ComplianceExpiryDate.Value).Date);
So this new json should look like this.
{
"metadata":{
"TotalCount":11,
"CurrentPageNumber":1,
},
"records":[
{
"offerId":"e1b75d86-67b1-4557-a381-5474383da3fb",
"isContract":true,
"transportRouteId":"e1b75d86-67b1-4557-a381-5474383da3fb",
"transportOrderId":"SEZYMY-210720-010097",
"schedule":null,
"carrierExpiredDate": (carrierExpiredDate.ComplianceExpiryDate.Value).Date)
},
]
}
var json =
#"{
"metadata":{
"TotalCount":11,
"CurrentPageNumber":1,
},
"records":[
{
"offerId":"e1b75d86-67b1-4557-a381-5474383da3fb",
"isContract":true,
"transportRouteId":"e1b75d86-67b1-4557-a381-5474383da3fb",
"transportOrderId":"SEZYMY-210720-010097",
"schedule":null
},
]
}";
var jObject = JObject.Parse(json);
var jList=jObject["records"].Children().ToList();
foreach(var jtoken in jList)
{
jtoken["carrierExpiredDat"] = (carrierExpiredDate.ComplianceExpiryDate.Value).Date));
}
string output = Newtonsoft.Json.JsonConvert.SerializeObject(jObject, Newtonsoft.Json.Formatting.Indented);
Try this. The code was tested using Visual Studio and Postman
.....
var expDate=DateTime.Now;
var json = await response.Content.ReadAsStringAsync()
var deserializedJson = JsonConvert.DeserializeObject<TransportRoot>(json);
deserializedJson.Records.ForEach(i=> i.carrierExpiredDate=expDate);
var newJson= JsonConvert.SerializeObject(deserializedJson);
classes
public class Metadata
{
public int TotalCount { get; set; }
public int CurrentPageNumber { get; set; }
}
public class Record
{
public string offerId { get; set; }
public bool isContract { get; set; }
public string transportRouteId { get; set; }
public string transportOrderId { get; set; }
public object schedule { get; set; },
public object carrierExpiredDate { get; set; }
}
public class TransportRoot
{
public Metadata Metadata { get; set; }
public List<Record> Records { get; set; }
}
if you have a problem with a camel case json, I highly recommend to change your startup
services.AddControllers()
// or services.AddControllersWithViews()
.AddNewtonsoftJson(options =>
options.SerializerSettings.ContractResolver =
new CamelCasePropertyNamesContractResolver());
I want to update the single document in collection with the guid as filter and update value is cityType. Every guid has different citytype here i have used 3 types it may be more.
So please give a right implementation using c# code.
Models:
public class Country
{
[BsonId]
public ObjectId Id { get; set; }
public int CountryId {get; set; }
public IEnumerable<States> States { get; set; }
}
public class States
{
public Guid Guid { get; set; }
public CityType CityType { get; set; }
}
Enum CityType
{
Unknown = 0,
Rural = 1,
Urban = 2
}
Existing Collection:
{
"_id": ObjectId("6903ea4d2df0c5659334e763"),
"CountryId": 200,
"States": [
{
"Guid": "AFCC4BE7-7585-5E46-A639-52F0537895D8",
"CityType": 0,
},
{
"Guid": "208FB603-08C7-46D9-B0C0-7AF4F691A96D",
"CityType": 0,
}
}
Input:
List<States>()
{
new States()
{
Guid = "AFCC4BE7-7585-5E46-A639-52F0537895D8",
CityType = CityType.Rural
},
new States()
{
Guid = "208FB603-08C7-46D9-B0C0-7AF4F691A96D",
CityType = CityType.Urban
}
}
Expected:
{
"_id": ObjectId("6903ea4d2df0c5659334e763"),
"CountryId": 200,
"States": [
{
"Guid": "AFCC4BE7-7585-5E46-A639-52F0537895D8",
"CityType": 1,
},
{
"Guid": "208FB603-08C7-46D9-B0C0-7AF4F691A96D",
"CityType": 2,
}
}
This is the method I have tried:
public async Task<bool> UpdateType(int countryId, IEnumerable<States> states)
{
var collection = connectionFactory.GetCollection<Country>(collectionName);
var cityTypes = states.Select(x => x.CityType);
var filter = Builders<Country>.Filter.Empty;
var update = Builders<Country>.Update.Set("States.$[edit].CityType", cityTypes);
var arrayFilters = new List<ArrayFilterDefinition>();
foreach (var state in states)
{
ArrayFilterDefinition<Country> optionsFilter = new BsonDocument("state.Guid", new BsonDocument("$eq", state.Guid));
arrayFilters.Add(optionsFilter);
}
var updateOptions = new UpdateOptions { ArrayFilters = arrayFilters };
var result = await collection.UpdateOneAsync(filter, update, updateOptions);
return result;
}
hope all details I have added here. Thanks in advance.
You don't have to loop through it:
Let's say you have a Class1 like this:
class Question : AuditableEntity {
public string Text { get; set; }
public List<string> Tags { get; set; } = new List<string>();
so you just say:
await collection.UpdateOneAsync(
someFilter,
Builders<Class1>.Update
.Set(f => f.Text, request.Question.Text)
.Set(f => f.Tags, request.Question.Tags));
This is my code in adding Fulfillment to Shopify orders but the converted json is not as expected.
Fullfillment product = new Fullfillment();
product.status = "success";
product.tracking_number = orderSent.TrackingNo;
List<LineItems> items = new List<LineItems>();
foreach (var item in orderSent.OrderLines)
{
LineItems line = new LineItems();
line.id = item.ProductName;
items.Add(line);
}
var json = JsonConvert.SerializeObject(product);
json = "{ \"fulfillment\": " + json + "}";
var json1 = JsonConvert.SerializeObject(items);
json = json + "{ \"line_items\": " + json1 + "}";
And this the converted json from this code:
{ "fulfillment": {
"id":0,
"status":"success",
"tracking_number":"xxxx12222",
}}{
"line_items": [
{
"id":"1234566645"
}
]
}
How can I turned like this:
{
"fulfillment": {
"tracking_number": null,
"line_items": [
{
"id": 466157049,
"quantity": 1
}
]
}
}
Model:
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public class Fullfillment
{
[JsonProperty(PropertyName = "id")]
public long id { get; set; }
[JsonProperty(PropertyName = "status")]
public string status { get; set; }
[JsonProperty(PropertyName = "tracking_number")]
public string tracking_number { get; set; }
}
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public class LineItems
{
[JsonProperty(PropertyName = "id")]
public string id { get; set; }
}
These are the models for Fulfillment and Line Items.
Thank you in advance for giving advices and help.
This works for me:
var json = JsonConvert.SerializeObject(new
{
fullfillment = new
{
product.tracking_number,
line_items = items.Select(x => new
{
x.id,
quantity = 1
})
}
});
That gives me:
{
"fullfillment" : {
"tracking_number" : "xxxx12222",
"line_items" : [{
"id" : "1234566645",
"quantity" : 1
}
]
}
}
I started with this code to build up the JSON above:
Fullfillment product = new Fullfillment();
product.status = "success";
product.tracking_number = "xxxx12222";
List<LineItems> items = new List<LineItems>();
LineItems line = new LineItems();
line.id = "1234566645";
items.Add(line);
Obviously you need to fill in your specific data.
Change your classes like below.
public class Rootobject
{
public Fulfillment fulfillment { get; set; }
}
public class Fulfillment
{
public string tracking_number { get; set; }
public Line_Items[] line_items { get; set; }
}
public class Line_Items
{
public string id { get; set; }
public int quantity { get; set; }
}
public class JsonTest
{
public void Test()
{
var root = new Rootobject();
root.fulfillment = new Fulfillment();
root.fulfillment.tracking_number = "xxxx12222";
root.fulfillment.line_items = new List<Line_Items>() { new Line_Items() { id = "1234566645", quantity = 1 } }.ToArray();
var json = JsonConvert.SerializeObject(root);
Console.WriteLine(json);
}
}
This will give you this json.
{
"fulfillment": {
"tracking_number": "xxxx12222",
"line_items": [
{
"id": "1234566645",
"quantity": 1
}
]
}
}
Try the following
public class Rootobject
{
public Fulfillment fulfillment { get; set; }
}
public class Fulfillment
{
public string tracking_number { get; set; }
public Line_Items[] line_items { get; set; }
}
public class Line_Items
{
public string id { get; set; }
public int quantity { get; set; }
}
public class JsonTest
{
public void Test()
{
var root = new Rootobject();
root.fulfillment = new Fulfillment();
root.fulfillment.tracking_number = "xxxx12222";
root.fulfillment.line_items = new List<Line_Items>() { new Line_Items() { id = "1234566645", quantity = 1 } }.ToArray();
var json = JsonConvert.SerializeObject(root);
Console.WriteLine(json);
}
}
My JSON looks like this:
[
{
"id": 001,
"name": "Item 1",
"tree": [
"010",
"020",
"030"
]
},
{
"id": 002,
"name": "Item 2",
"tree": [
"010",
"020",
"030"
]
},
{
"id": 003,
"name": "Item 3",
"tree": [
"010",
"020",
"030"
]
}
]
This can be modelled into C# as following:
public class Product
{
public int id { get; set; }
public string name { get; set; }
public List<string> tree { get; set; }
}
I'm trying to display this JSON data into a TreeListView in the ObjectListView libary. Ideally, it would look like this.
My current code is as following, with "data" being the TreeListView.
List<Product> Products = JsonConvert.DeserializeObject<List<Product>>(json);
data.CanExpandGetter = model => ((Product)model).tree.Count > 0;
data.ChildrenGetter = delegate(object model)
{
return ((Product)model).
tree;
};
data.SetObjects(Products);
However, this throws an System.InvalidCastException at model => ((Product)model).tree.Count > 0.
I found the solution. I changed the JSON layout a bit.
public class ProductJSON
{
public string id { get; set; }
public string name { get; set; }
public List<Tree> tree { get; set; }
}
public class Tree
{
public string id { get; set; }
public string name { get; set; }
}
public class Product
{
public string id { get; set; }
public string name { get; set; }
public List<Product> tree { get; set; }
public Product(string _id, string _name)
{
id = _id;
name = _name;
tree = new List<Product>();
}
}
...
List<ProductJSON> Products = JsonConvert.DeserializeObject<List<ProductJSON>>(json);
List<Product> ProductList = new List<Product>();
for(int i = 0; i < Products.Count; i++)
{
ProductList.Add(new Product(Products[i].id, Products[i].name));
foreach (Tree t in Products[i].tree)
{
ProductList[i].tree.Add(new Product(t.id, t.name));
}
}
data.CanExpandGetter = delegate(object x) { return true; };
data.ChildrenGetter = delegate(object x) { return ((Product)x).tree; };
cID.AspectGetter = delegate(object x) { return String.Format("{0,3:D3}", ((Product)x).id); };
cName.AspectGetter = delegate(object x) { return ((Product)x).name; };
data.Roots = ProductList;