Issue regarding json array - c#

I have a JSON array and I am adding items. I want to display this JSON in a particular format.
My code:
var array = new List<object>();
array.Add(new
{
Dealname = dealname,
Ticketcount = tictnum,
OriginalPrice = origpri,
Dealsticketcount = dealsticktnu,
dealprice = dp,
totalprice = totamnt,
});
array.Add(new
{
ItemName = itnme,
Price = price,
Quantity = quant,
});
This is what my array looks like. I am adding some items. Right now it produces the following output:
[{"Dealname":"unnideal","Ticketcount":"25","OriginalPrice":"100","Dealsticketcount":"1","dealprice":"200","totalprice":"300},{"ItemName":"popcorn","Price":"100","Quantity":"1"},{"ItemName":"piza","Price":"100","Quantity":"1"}]
But i need my output like this:
[{"Dealname":"unnideal","Ticketcount":"25","OriginalPrice":"100","Dealsticketcount":"1","dealprice":"200","totalprice":"300"},"Offers"[{"ItemName":"popcorn","Price":"100","Quantity":"1"},{"ItemName":"piza","Price":"100","Quantity":"1"}]]
That is, I need an array for offers. How can I make this possible?

Your problem appears to be that your parent object, and child "offer" objects are not related, when Offers needs to be part of the main object.
Try something like this:
var array = new List<object>();
var offers = new List<object>();
offers.Add(new
{
ItemName = itnme,
Price = price,
Quantity = quant,
});
array.Add(new
{
Dealname = dealname,
Ticketcount = tictnum,
OriginalPrice = origpri,
Dealsticketcount = dealsticktnu,
dealprice = dp,
totalprice = totamnt,
Offers = offers
});

Sounds like you just want another property named "Offers"?
var array = new List<object>();
var offers = new[]
{
new {ItemName = itnme, Price = price, Quantity = quant}
...
};
array.Add(new
{
Dealname = dealname,
Ticketcount = tictnum,
OriginalPrice = origpri,
Dealsticketcount = dealsticktnu,
dealprice = dp,
totalprice = totamnt,
Offers = offers // adding Offers as a property here
});
This should produce a JSON like the following:
[
{
"Dealname": "unnideal",
"Ticketcount": "25",
"OriginalPrice": "100",
"Dealsticketcount": "1",
"dealprice": "200",
"totalprice": "300",
"Offers": [
{
"ItemName": "popcorn",
"Price": "100",
"Quantity": "1"
},
{
"ItemName": "piza",
"Price": "100",
"Quantity": "1"
}
]
}
]

Related

How can I easily create readable JSON objects in C# .Net Core similar to JavaScript

In JavaScript I can easily create an object and assign variables with some very basic notation such as:
const Object = JSON.parse('
{
"something": outsideVariable,
"someArray": [
"hey",
"there"
]
}
');
Is there a simple way to do this with C# that is clean and easy to assign variables too? I experimented a bit with the JsonObject but the code for that looks needlessly messy, for example:
JsonObject jsonPayload = new JsonObject
{
["documentId"] = documentID,
["testMode"] = true,
["signers"] = new JsonArray
{
new JsonObject
{
["label"] = "John Smith",
["contactMethod"] = new JsonArray
{
new JsonObject
{
["type"] = "link"
}
}
}
}
};
I also tried using the literal symbol (#) with a string, but it ends up injecting carriage returns and linefeeds, and inserting variables winds of being a great deal of concatination.
IMHO , the most close you want is this
var jsonPayload = new
{
documentId = 1,
testMode = true,
signers = new object[]
{
new {
label="John Smith",
contactMethod= new object[]
{
new {
type="link"
}
}
}
}
};
and code
var json= System.Text.Json.JsonSerializer
.Serialize(jsonPayload,new JsonSerializerOptions { WriteIndented = true });
//or if you need
var jsonParsed= JsonDocument.Parse(json);
result
{
"documentId": 1,
"testMode": true,
"signers": [
{
"label": "John Smith",
"contactMethod": [
{
"type": "link"
}
]
}
]
}

Joining List of item

I want to achieve the below format data from to different List.
Using the below code:
List<SalesOrder> SalesOrder = new List<SalesOrder>();
List<Sales> Sales = new List<Sales>();
SalesOrder.Add(new SalesOrder { VoucherNumber = "1", Date = "01-04-2018", LedgerName = "Sales Party", Refernce = "1", StockItem = "Item 1", Description = "", qnt = "1200", Rate = "120", Amount = "14000" });
SalesOrder.Add(new SalesOrder { VoucherNumber = "1", Date = "01-04-2018", LedgerName = "Sales Party", Refernce = "1", StockItem = "Item 2", Description = "", qnt = "78", Rate = "980", Amount = "76440" });
SalesOrder.Add(new SalesOrder { VoucherNumber = "2", Date = "04-04-2018", LedgerName = "Sales Party", Refernce = "2", StockItem = "Item 3", Description = "", qnt = "350", Rate = "345", Amount = "120750" });
Sales.Add(new Sales { VoucherNumber = "1", Date = "05-04-2018", Refernce = "1", LedgerName = "SalePartyLedgerName", Description = "", qnt = "100 nos", Rate = "120", Amount = "12000" });
Sales.Add(new Sales { VoucherNumber = "1", Date = "05-04-2018", Refernce = "1", LedgerName = "SalePartyLedgerName", Description = "", qnt = "40 nos", Rate = "980", Amount = "39200" });
var res = from so in SalesOrder
join s in Sales
on so.VoucherNumber equals s.Refernce into ps
from s in ps.DefaultIfEmpty()
select new
{
SONO = so.VoucherNumber,
SODate = so.Date,
SoCustomer = so.LedgerName,
SoItem = so.StockItem,
SoDescription = so.Description,
SoUnit = so.qnt,
SoRate = so.Rate,
SoAmount = so.Amount,
SInvNum = s?.VoucherNumber ?? string.Empty,
SDate = s?.Date ?? string.Empty,
SQnt = s?.qnt ?? string.Empty,
SRate = s?.Rate ?? string.Empty,
SAmount = s?.Amount ?? string.Empty
};
I am getting the following result:
I want to merge those two List's based on a ref number. Currently what i have tried is based on left join but the item is getting repeated by number of item present in the 2nd list. You may note that 1st image show only 2 line of data containing "1" as a number and my c# code is creating 4 of them and data is also getting repeated and spitted in next line too.
What changes i need to do for getting the result what i want?
Any help with an example will be greatly appreciated.
Sorry for my bad English.

How create the filters in Function Score Query with .NET NEST Client

In Elasticsearch Document describe about Function Score Query show code as below
GET /_search
{
"query": {
"function_score": {
"query": { "match_all": {} },
"boost": "5",
"functions": [
{
"filter": { "match": { "test": "bar" } },
"random_score": {},
"weight": 23
},
{
"filter": { "match": { "test": "cat" } },
"weight": 42
}
],
"max_boost": 42,
"score_mode": "max",
"boost_mode": "multiply",
"min_score" : 42
}
}
}
I write this query to object initializer syntax
var searchRequest = new SearchRequest<ProductType>
{
Query = new FunctionScoreQuery()
{
Query = new MatchAllQuery {},
Boost = 5,
Functions = new List<IScoreFunction>
{
Filters...?
},
MaxBoost = 42,
ScoreMode = FunctionScoreMode.Max,
BoostMode = FunctionBoostMode.Max,
MinScore = 42
}
};
How to build filters in Functions?
The IScoreFunction interface allow only ExponentialDecayFunction, GaussDateDecayFunction, LinearGeoDecayFunction, FieldValueFactorFunction, RandomScoreFunction, WeightFunction, ScriptScoreFunction
Functions is a collection of IScoreFunction. In the example JSON, the first function is a random score function, and the second, a weight function. The linked Query DSL example has examples of the different functions, and here's an example to match the JSON above
var client = new ElasticClient();
var searchRequest = new SearchRequest<ProductType>
{
Query = new FunctionScoreQuery()
{
Query = new MatchAllQuery { },
Boost = 5,
Functions = new List<IScoreFunction>
{
new RandomScoreFunction
{
Filter = new MatchQuery
{
Field = "test",
Query = "bar"
},
Weight = 23
},
new WeightFunction
{
Filter = new MatchQuery
{
Field = "test",
Query = "cat"
},
Weight = 42
}
},
MaxBoost = 42,
ScoreMode = FunctionScoreMode.Max,
BoostMode = FunctionBoostMode.Multiply,
MinScore = 42
}
};
var searchResponse = client.Search<ProductType>(searchRequest);

Creating a json-style inside a linq select statement

In my MVC controller, I have the following linq query (which works fine):
var result = from li in lineItems
join r in rates on li.something = r.something
select new
{
li.something
li.somethingElse
li.another
r.something
r.somethingElse
r.rate1
r.rate2
r.rate3
r.rate4
};
return JSON(result.ToList(), JsonRequestBehavior.AllowGet);
And that generates a flat object just fine. However, what I really need is for the rates to be an object of their own, one layer deeper, like this:
{
li.something
li.somethingElse
li.another
r.something
r.somethingElse
rates = {
{id = "1", value = r.rate1}
{id = "2", value = r.rate2}
{id = "3", value = r.rate3}
{id = "4", value = r.rate4}
}
}
I'm having difficulty getting the C# syntax right to make that happen. Hardcoding the id is fine. I will always only have rate 1 2 3 and 4.
You can define 'rates' property as anonymous array of object, please see below sample for reference.
{
li.something,
li.somethingElse,
li.another,
r.something,
r.somethingElse,
rates = new[]{
new {id = "1", value = r.rate1},
new {id = "2", value = r.rate2},
new {id = "3", value = r.rate3},
new {id = "4", value = r.rate4}
}
}
I ended up doing this:
rates = new
{
Rate1 = new {id = "1", value = r.rate1}
Rate2 = new {id = "2", value = r.rate2}
Rate3 = new {id = "3", value = r.rate3}
Rate4 = new {id = "4", value = r.rate4}
}
Which didn't throw any errors. It named the JSON which I didn't really need but I guess it didn't hurt anything either.

Create nested json with c#

I am able to create a flat serialized JSON string pretty easily with c#
My issue is I want to create a nested string like this below
[ {
title: "Yes",
id : "1",
menu: [ {
title: "Maybe",
id : "3",
alert : "No",
menu: [ {
title: "Maybe Not",
id : "8",
alert : "No",
menu: []
} ]
} ]
},
{
title: "No",
id : "2",
menu: []
}]
Any help would be great
Are you using MVC 3? - Do something like:
return Json(myObectWithListProperties, JsonRequestBehavior.AllowGet);
I use this to return complex C# objects that match the structure of the JavaScript objects I want.
e.g.:
var bob = new {
name = "test",
orders = new [] {
new { itemNo = 1, description = "desc" },
new { itemNo = 2, description = "desc2" }
}
};
return Json(bob, JsonRequestBehavior.AllowGet);
gives:
{
"name": "test",
"orders": [
{
"itemNo": 1,
"description": "desc"
},
{
"itemNo": 2,
"description": "desc2"
}
]
}
EDIT: A bit more nesting for fun:
var bob = new {
name = "test",
orders = new [] {
new { itemNo = 1, description = "desc" },
new { itemNo = 2, description = "desc2" }
},
test = new {
a = new {
b = new {
something = "testing",
someOtherThing = new {
aProperty = "1",
another = "2",
theThird = new {
bob = "quiteDeepNesting"
}
}
}
}
}
};
return Json(bob, JsonRequestBehavior.AllowGet);
gives:
{
"name": "test",
"orders": [
{
"itemNo": 1,
"description": "desc"
},
{
"itemNo": 2,
"description": "desc2"
}
],
"test": {
"a": {
"b": {
"something": "testing",
"someOtherThing": {
"aProperty": "1",
"another": "2",
"theThird": {
"bob": "quiteDeepNesting"
}
}
}
}
}
}
Try using
using System.Web.Script.Serialization;
//Assumed code to connect to a DB and get data out using a Reader goes here
Object data = new {
a = reader.GetString(field1),
b = reader.GetString(field2),
c = reader.GetString(field3)
};
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string json = javaScriptSerializer.Serialize(data);
This is built-in and saves you the work of serializing to JSON yourself!
This example assumes you are getting data from a database using some sort of reader, and it then constructs the object you want to serialize using an anonymous class. Your anonymous class can be as simple or complex as you need it to be and the JavaScriptSerializer will handle transforming it to JSON. This approach is also useful because you can easily control the JSON property names it will create in the JSON.
using System.Web.Script.Serialization;
var strNJson = new
{
to = "hello",
notification = new
{
title = "textTitle",
body = "bodyText"
}
};
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string json = javaScriptSerializer.Serialize(strNJson);
{ "to":"hello",
"notification": {
"title":"titleText",
"body":"bodyText"
}
}
You can make use of the ExpandoObject under the System.Dynamic namespace.
Here is a small snippet for achieving your solution:
dynamic parameters = new dynamic[2];
parameters[0] = new ExpandoObject();
parameters[0].title = "Yes";
parameters[0].id = "1";
parameters[0].menu = new dynamic[1];
parameters[0].menu[0] = new ExpandoObject();
parameters[0].menu[0].title = "Maybe";
parameters[0].menu[0].id = "3";
parameters[0].menu[0].alert = "No";
parameters[0].menu[0].menu = new dynamic[1];
parameters[0].menu[0].menu[0] = new ExpandoObject();
parameters[0].menu[0].menu[0].title = "Maybe Not";
parameters[0].menu[0].menu[0].id = "8";
parameters[0].menu[0].menu[0].alert = "No";
parameters[0].menu[0].menu[0].menu = new dynamic[0];
parameters[1] = new ExpandoObject();
parameters[1].title = "No";
parameters[1].id = "2";
parameters[1].menu = new dynamic[0];
string json = JsonConvert.SerializeObject(parameters, Formatting.Indented);
Console.WriteLine(json);
Here is the work in fiddle
Note: There are other ways to achieve this, but I have been using this approach.

Categories

Resources