what is the best way to generate json from C# - c#

i am trying to mimic an example where they are using hard coded JSON
{
"page": 1,
"total": 1,
"records": 2,
"rows": [
{"id": 1, "cell": ["1", "Super Item", "300", 0, null, false, false]},
{"id": 2, "cell": ["2", "Item 1", "100", 1, 1, false, false]},
{"id": 3, "cell": ["3", "Sub Item 1", "50", 2, 2, true, true]},
{"id": 4, "cell": ["4", "Sub Item 2", "25", 2, 2, false, false]},
{"id": 5, "cell": ["5", "Sub-sub Item 1", "25", 3, 4, true, true]},
{"id": 6, "cell": ["6", "Sub Item 3", "25", 2, 2, true, true]},
{"id": 7, "cell": ["7", "Item 2", "200", 1, 1, false, false]},
{"id": 8, "cell": ["8", "Sub Item 1", "100", 2, 7, false, false]},
{"id": 9, "cell": ["9", "Sub-sub Item 1", "50", 3, 8, true, true]},
{"id": 10, "cell": ["10", "Sub-sub Item 2", "50", 3, 8, true, true]},
{"id": 11, "cell": ["11", "Sub Item 2", "100", 2, 7, true, true]}
]
}
but i need to generate this from C#. Are there any suggestions for the best way to go about generating this above in C#?

The Controller class has a Json method that serialises objects as JSON, so in your action method you just create the object and call the method:
public ActionResult GetData() {
return Json(
new {
page = 1,
total = 1,
records = 2,
rows = new[] {
new { id = 1, cell = new object[] { "1", "Super Item", "300", 0, null, false, false } },
new { id = 2, cell = new object[] { "2", "Item 1", "100", 1, 1, false, false } },
new { id = 3, cell = new object[] { "3", "Sub Item 1", "50", 2, 2, true, true } },
new { id = 4, cell = new object[] { "4", "Sub Item 2", "25", 2, 2, false, false } },
new { id = 5, cell = new object[] { "5", "Sub-sub Item 1", "25", 3, 4, true, true } },
new { id = 6, cell = new object[] { "6", "Sub Item 3", "25", 2, 2, true, true } },
new { id = 7, cell = new object[] { "7", "Item 2", "200", 1, 1, false, false } },
new { id = 8, cell = new object[] { "8", "Sub Item 1", "100", 2, 7, false, false } },
new { id = 9, cell = new object[] { "9", "Sub-sub Item 1", "50", 3, 8, true, true } },
new { id = 10, cell = new object[] { "10", "Sub-sub Item 2", "50", 3, 8, true, true } },
new { id = 11, cell = new object[] { "11", "Sub Item 2", "100", 2, 7, true, true } }
}
}
);
}

There's a class built into .Net 2+ which is called 'JavaScriptSerializer' which creates a JSON structured string based on a .Net typed class.
Using the serializer you can simply created a class with properties and collections to represent your JSON data. Create an instance of it in .Net server side code and then respond using the serializer to generate a valid JSON string response.
Here's an example of converting a Person class instance to a serialized JSON string;
JavaScriptSerializer js = new JavaScriptSerializer();
Person p1 = new Person();
p1.firstName = "Brian";
p1.lastName = "Scott";
p1.department = "Microsoft";
p1.address.addressline1 = "Microsoft";
p1.address.addressline2 = "";
p1.address.city = "Redmond";
p1.address.state = "Seattle";
p1.address.country = "America";
p1.address.pin = 560028;
p1.technologies = new string[] { "IIS", "ASP.NET", "JavaScript", "AJAX" };
string strJSON = js.Serialize(p1);
This will produce a valid JSON string of
{"firstName":"Brian","lastName":"Scott","department":"Microsoft","address":{"addressline1":"Microsoft","addressline2":"","city":"Redmond","state":"Seattle","country":"America","pin":560028},"technologies":["IIS","ASP.NET","JavaScript","AJAX"]}
If you are intending to use a webservice to produce the JSON response to the client side then you can mark your method as;
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetPersonJSON()
{
JavaScriptSerializer js = new JavaScriptSerializer();
Person p1 = new Person();
p1.firstName = "Brian";
p1.lastName = "Scott";
p1.department = "Microsoft";
p1.address.addressline1 = "Microsoft";
p1.address.addressline2 = "";
p1.address.city = "Redmond";
p1.address.state = "Seattle";
p1.address.country = "America";
p1.address.pin = 560028;
p1.technologies = new string[] { "IIS", "ASP.NET", "JavaScript", "AJAX" };
return js.Serialize(p1);
}

Apparently you are trying to populate a jqGrid and you're using ASP.NET MVC.
If you have defined a class for these values:
["1", "Super Item", "300", 0, null, false, false]
You can store all the elements in a collection myCollection
you can do something like this:
var ReturnData = new
{
total = totalPages,
page = page,
records = totalRecords,
rows = myCollection.Select(r => new
{
id = r.Id.ToString(),
cell = new String[] { r.Field1, r.Field2, r.Field3, r.Field4 }
})
};
return (Json(ReturnData, JsonRequestBehavior.DenyGet));

class Row {
public int id {get;set;}
public object[] cell {get;set;}
}
class Data {
public int page {get;set;}
public int total {get;set;}
public int records {get;set;}
public Row[] rows {get;set;}
}
var myData = new Data(){ .... };
var json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(myData);

Related

Net Core API not returning all children DB First

Below is my code. I'm wondering if I might be better off using something else. I feel like this should be a fairly simple return.
Repository:
public Task<OrderHistory> GetInvoicedMacolaOrder(string orderNumber)
{
orderNumber = " " + orderNumber;
DataContext.ChangeTracker.LazyLoadingEnabled = false;
var order = DataContext.OrderHistory
.Include(order => order.OrderLines)
.ThenInclude(line => line.vw_uniqueCartonIds)
.FirstOrDefaultAsync(o => o.ord_no == orderNumber);
return order;
}
OrderHistoryController:
[Authorize(Policy = "CreateReplacementOrder")]
[HttpGet("invoicedorder/{orderNumber}/get")]
public async Task<IActionResult> OrderLookUp(string orderNumber)
{
if (PoExists(orderNumber))
{
var order = await _mrepo.GetInvoicedOrder(orderNumber);
var orderToReturn = _mapper.Map<OrderHistoryDtoDetail>(order);
return Ok(orderToReturn);
}
else
{
return BadRequest("Could not find order number.");
}
}
This is what returns:
{
"ord_no": "51464326",
"status": "P",
"ord_dt": "2020-03-29T00:00:00",
"apply_to_no": null,
"oe_po_no": "3804339 ",
"cus_no": "65564654018",
"ship_to_name": "Omar Brown"
"OrderLines": [
{
"ord_type": "O",
"ord_no": "51464326",
"line_seq_no": 1,
"item_no": "jkhhuk",
"line_no": 1,
"vw_uniqueCartonIds": [
{
"box_id": 20,
"prod_cat": "044",
"box_number": 1,
"uniqueBoxID": "100001"
},
{
"box_id": 20,
"prod_cat": "044",
"box_number": 2,
"uniqueBoxID": "100002"
},
{
"box_id": 20,
"prod_cat": "044",
"box_number": 3,
"uniqueBoxID": "100003"
}
]
}
]
}
What I'm expecting:
{
"ord_no": "51464326",
"status": "P",
"ord_dt": "2020-03-29T00:00:00",
"apply_to_no": null,
"oe_po_no": "3804339 ",
"cus_no": "65564654018",
"ship_to_name": "Omar Brown"
"OrderLines": [
{
"ord_type": "O",
"ord_no": "51464326",
"line_seq_no": 1,
"item_no": "jkhhuk",
"line_no": 1,
"vw_uniqueCartonIds": [
{
"box_id": 20,
"prod_cat": "044",
"box_number": 1,
"uniqueBoxID": "100001"
},
{
"box_id": 21,
"prod_cat": "044",
"box_number": 2,
"uniqueBoxID": "100002"
},
{
"box_id": 22,
"prod_cat": "044",
"box_number": 3,
"uniqueBoxID": "100003"
}
]
},
{
"ord_type": "O",
"ord_no": "51464326",
"line_seq_no": 2,
"item_no": "58hhuk",
"line_no": 2,
"vw_uniqueCartonIds": [
{
"box_id": 25,
"prod_cat": "054",
"box_number": 1,
"uniqueBoxID": "200001"
},
{
"box_id": 26,
"prod_cat": "054",
"box_number": 2,
"uniqueBoxID": "200002"
}
]
}
]
}
Also I have seen the posts about ReferenceLoopHandling and added that to my startup.cs file,but to no avail.
services.AddControllers(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
})
.AddNewtonsoftJson(opt =>
{
opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
What causes the problem?

How can I filter Mongodb specific document's subdocument

Consider you have Order and OrderDetails. I'm trying to filter order details for the specific order.
For instance if you have document something like this:
{
"orders": [
{
"id": 1,
"date": "02.04.2020 ...",
"user": {
"name": "xx",
"surname": "yy"
},
"orderDetails": [
{
"id": 1,
"productId": 5,
"quantity": 1,
"state": 3
},
{
"id": 2,
"productId": 3,
"quantity": 4,
"state": 3
},
{
"id": 3,
"productId": 4,
"quantity": 12,
"state": 2
},
{
"id": 4,
"productId": 7,
"quantity": 8,
"state": 2
},
{
"id": 5,
"productId": 12,
"quantity": 9,
"state": 3
}
]
},
{
"id": 2,
"date": "01.04.2020 ...",
"user": {
"name": "xx",
"surname": "yy"
},
"orderDetails": [
{
"id": 6,
"productId": 5,
"quantity": 1,
"state": 3
},
{
"id": 7,
"productId": 3,
"quantity": 4,
"state": 3
},
{
"id": 8,
"productId": 4,
"quantity": 12,
"state": 2
}
]
}
}
What I'm trying to do is first filtering by order and then state of an order detail. I have a code like this but it always brings correct order with all orderDetails. Seems like it doesn't care about equal filter for orderDetails.
Actually it's working but not filtering. Because I only have 3 types of state(enum) and int values are 1,2,3. Query brings nothing if I give 4.
var builder = Builders<Order>.Filter;
var filter = builderk.And(builder.Eq("_id", ObjectId.Parse(elementid)), builder.Eq("orderDetails.state", 3));
var result = _mongoRepository.FindByFilter(filter).ToList();
I also tried AnyEq and something like that filters but didn't work.
I will be very happy if anyone can help me.
Thanks.
You can use aggregation operation for operations such as filter sorting in detail records.
If we continue through the sample, you must first create a filter for your master data.
var builderMaster = Builders<Order>.Filter;
var filterMaster = builderMaster.Eq("_id", ObjectId.Parse(elementid));
Then you need to create a different filter for the details.
Important: You must use the BsonDocument type when creating detail filters. Because you cannot give a specific type when you filter the details.
var builderDetail = Builders<BsonDocument>.Filter;
var filterDetail = builderDetail.Eq("orderDetails.state", 3);
Then you can start typing the query.
var list = _mongoRepository.Aggregate()
.Match(filterMaster)
.Unwind("orderDetails")// Name the details.
.Match(filterDetail)
.Sort(sort)// optionally
.Skip(skip) // optionally
.Limit(limit) // optionally
.ToList();
It will give you a list of BsonDocument with the given parameters. After that, you have to map with your own detail class.
var resultList = new List<OrderDetails>();
foreach (var master in list)
{
var masterObj = BsonSerializer.Deserialize<dynamic>(master);
foreach (var item in masterObj)
{
if (item.Key == "orderDetails")
{
var mapper = new MapperConfiguration(cfg => { }).CreateMapper();
var retItem = mapper.Map<OrderDetails>(item.Value);
resultList.Add(retItem);
}
}
}

Extract objects from JSON array with Newtonsoft JSON

I have a JSON data like bellow
[{
"CurrencyDenomination_JSON": "[{\"PK_MasterCurrencyDenomID\":1,\"CurrencyDenomination\":2000,\"NoofCurrency\":2,\"Total\":\"4000.00\",\"IsNote\":true},{\"PK_MasterCurrencyDenomID\":2,\"CurrencyDenomination\":500,\"NoofCurrency\":2,\"Total\":\"1000.00\",\"IsNote\":true}]"
}, {
"CurrencyDenomination_JSON": "[{\"PK_MasterCurrencyDenomID\":1,\"CurrencyDenomination\":2000,\"NoofCurrency\":5,\"Total\":\"10000.00\",\"IsNote\":true},{\"PK_MasterCurrencyDenomID\":2,\"CurrencyDenomination\":500,\"NoofCurrency\":2,\"Total\":\"1000.00\",\"IsNote\":true}]"
}, {
"CurrencyDenomination_JSON": "[{\"PK_MasterCurrencyDenomID\":1,\"CurrencyDenomination\":2000,\"NoofCurrency\":5,\"Total\":\"10000.00\",\"IsNote\":true},{\"PK_MasterCurrencyDenomID\":2,\"CurrencyDenomination\":500,\"NoofCurrency\":5,\"Total\":\"2500.00\",\"IsNote\":true}]"
}]
and I want to extract value from it and expect bellow data
[{
"PK_MasterCurrencyDenomID": 1,
"CurrencyDenomination": 2000,
"NoofCurrency": 2,
"Total": "4000.00",
"IsNote": true
}, {
"PK_MasterCurrencyDenomID": 2,
"CurrencyDenomination": 500,
"NoofCurrency": 2,
"Total": "1000.00",
"IsNote": true
}, {
"PK_MasterCurrencyDenomID": 3,
"CurrencyDenomination": 200,
"NoofCurrency": 2,
"Total": "400.00",
"IsNote": true
}, {
"PK_MasterCurrencyDenomID": 4,
"CurrencyDenomination": 100,
"NoofCurrency": 2,
"Total": "200.00",
"IsNote": true
}, {
"PK_MasterCurrencyDenomID": 5,
"CurrencyDenomination": 50,
"NoofCurrency": 2,
"Total": "100.00",
"IsNote": true
}, {
"PK_MasterCurrencyDenomID": 6,
"CurrencyDenomination": 20,
"NoofCurrency": 2,
"Total": "40.00",
"IsNote": true
}]
to do that I write bellow code ,and think this is not right way to do that there must be some smart way to do that .Please suggest me a better alternative.
JArray jsonArray = JArray.Parse(json);
List<MasterCurrencyDenomination> d = new List<MasterCurrencyDenomination>();
string strjson = string.Empty;
foreach (var item in jsonArray.Children())
{
strjson+= item["CurrencyDenomination_JSON"].ToString().Replace("[", "").Replace("]", ",");
}
d = JsonConvert.DeserializeObject<List<MasterCurrencyDenomination>>("["+strjson+"]");
If you observe the Json, it is evident that it is an Array of Type which contains a single String Property CurrencyDenomination_JSON. The Value of CurrencyDenomination_JSON is a JSON string.
What you need to do is, fetch these JSON strings (represented as IEnumerable<string>), retrieve JObject from them by parsing each of them and Serialize the collection.
var currencyArray = JArray.Parse(json).Children<JObject>()
.SelectMany(x=>x.Properties().Select(c=>c.Value.Value<string>()));
var result = JsonConvert.SerializeObject(currencyArray.SelectMany(x=>JArray.Parse(x)));
I think You can use the following code to do this.
List<MasterCurrencyDenomination> items = new List<MasterCurrencyDenomination>();
JToken.Parse(myJson).ToList().ForEach(x =>
{
items.AddRange(JsonConvert.DeserializeObject<List<MasterCurrencyDenomination>>(x.SelectToken("CurrencyDenomination_JSON").Value<string>()));
});
OR:
List<MasterCurrencyDenomination> items2 = new List<MasterCurrencyDenomination>();
foreach (var test in JToken.Parse(myJson))
{
items2.AddRange(JsonConvert.DeserializeObject<List<MasterCurrencyDenomination>>(test.SelectToken("CurrencyDenomination_JSON").Value<string>()));
}

Why OrderBy does not sort the data?

I want to group and sort data, but OrderBy function is not working as it should, and I'm wondering what I'm doing wrong
Code:
var data = new List<PreparedData>() {
new PreparedData {
IsGroup = false,
Service = "Number 5",
Name = "Banana",
SomeValue = 5,
},
new PreparedData {
IsGroup = false,
Service = "Number 5",
Name = "Apple",
SomeValue = 5,
},
new PreparedData {
IsGroup = false,
Service = "Number 3",
Name = "Apple",
SomeValue = 5,
},
new PreparedData {
IsGroup = false,
Service = "Number 3",
Name = "Blueberry",
SomeValue = 9,
},
new PreparedData {
IsGroup = true,
Service = "Number 9",
Name = "Garlic",
SomeValue = 7,
}
}
var groupedAndSortedData = data.GroupBy(x => x.IsGroup).Select(isGroup => new FruitViewData
{
IsGroup = isGroup.Key,
FruitData = isGroup.GroupBy(s => s.Service).Select(service => new FruitServiceData
{
Service = service.OrderBy(z => z.Service).First().Service,
FruitTypeData = service.OrderBy(x => x.Name).Select(fruitType => new FruitTypeData
{
Name = fruitType.Name,
SomeValue = fruitType.SomeValue
}
}
}
At the end I get:
[
{
IsGroup: false
FruitData: [
{
Service: "Number 5",
FruitTypeData: [
{
Name: "Banana",
SomeValue = 5,
},
{
Name: "Apple",
SomeValue = 5,
},
]
},
{
Service: "Number 3",
FruitTypeData: [
{
Name: "Apple",
SomeValue = 5,
},
{
Name: "Blueberry",
SomeValue = 9,
},
]
]
},
{
IsGroup: true
FruitData: [
{
Service: "Number 9",
FruitTypeData: [
{
Name: "Garlic",
SomeValue = 9,
}
]
},
]
},
]
But I would like to get sorted data like:
[
{
IsGroup: false
FruitData: [
{
Service: "Number 3",
FruitTypeData: [
{
Name: "Apple",
SomeValue = 5,
},
{
Name: "Blueberry",
SomeValue = 9,
},
]
},
{
Service: "Number 5",
FruitTypeData: [
{
Name: "Apple",
SomeValue = 5,
},
{
Name: "Banana",
SomeValue = 5,
},
]
},
]
},
{
IsGroup: true
FruitData: [
{
Service: "Number 9",
FruitTypeData: [
{
Name: "Garlic",
SomeValue = 9,
}
]
},
]
},
]
I tried to sort it in a different way like for example using the foreach loop after groupedAndSortedData and add OrderBy function to every iteration but also without satisfactory effect
What should I change to get the expected result?
It looks to me like you need to order the FruitData results:
var groupedAndSortedData = data.GroupBy(x => x.IsGroup).Select(isGroup => new FruitViewData
{
IsGroup = isGroup.Key,
FruitData = isGroup.GroupBy(s => s.Service).Select(service => new FruitServiceData
{
Service = service.OrderBy(z => z.Service).First().Service,
FruitTypeData = service.OrderBy(x => x.Name).Select(fruitType => new FruitTypeData
{
Name = fruitType.Name,
SomeValue = fruitType.SomeValue
})
}).OrderBy(fd => fd.Service) //This here
});
Notice the .OrderBy(fd => fd.Service) method call.

How can show JSON array data in dropdown list in asp.net c#?

I want to populate JSON array data in a dropdown list in asp.net. My json Array is,
"Product": [
{
"id": 0,
"productId": 0,
"quantity": 20,
"productName": "Rawai",
"brandName": "Kamal Products",
"productCode": 0,
"brandId": 0,
"productPrice": 0
},
{
"id": 0,
"productId": 0,
"quantity": 22,
"productName": "OIL",
"brandName": "Kamal Proucts",
"productCode": 0,
"brandId": 0,
"productPrice": 0
},
{
"id": 0,
"productId": 0,
"quantity": 3,
"productName": "Ghee",
"brandName": "Kamal Products",
"productCode": 0,
"brandId": 0,
"productPrice": 0
}
]
I am getting URLand from URL I get JSON array
Product lstProduct = new Product();
List lstBrandProduct = new List();
string urls = new System.Net.WebClient().DownloadString(urlnames);
JArray jsonArrays = JArray.Parse(urls);
for (int i = 0; i < jsonArrays.Count; i++)
{
CustomerOrder isiData = (new JavaScriptSerializer()).Deserialize<CustomerOrder>(jsonArrays[i].ToString());
for (int j = 0; j < isiData.product.Count; j++)
{
drpListBrand.DataTextField = isiData.product[j].BrandName;
}
}
I want to show the 'product Name' in the dropdown list how can I show?
You can use NewtonSoft.JSON Nuget
var files = JObject.Parse(YourJson);
var recList = files.SelectTokens("$").ToList();
foreach (JProperty item in recList.Children())
{
var key = item.Name.ToString(); //store the root item
var value= item.Value.ToString();
var breakitem = item.Values().ToList();
for (int i = 0; i < breakitem.Count; i++)
{
string drpvalue = breakitem[i]["productName"].ToString();
//ADD this value to your dropdownList Object
}
}

Categories

Resources