how to create a json format using json.net in c# - c#

I need a final json format as follows and that should be dynamic.
{
"product_items" :
[
{
"_at" : 1,
"product_id" : "999"
},
{
"_at" : 2,
"quantity" : 2.00
},
{
"_delete_at" : 3
}
]
}
How to create a json format as above in the code._at field is dynamic.sometimes it might be 2 and sometimes it might be 10.I dont have idea on to generate the json dynamically in c#.
class Test
{
public ProductItem[] product_items { get; set; }
class ProductItem
{
public int[] _at { get; set; }
public int[] _delete { get; set; }
public int[] quantity { get; set; }
public string[] product_id{get;set;}
}
}
i have create the the properties for json as above.

I'm using Newtonsoft library
Your class should look more like this:
public class ProductItem
{
public int _at { get; set; }
public string product_id { get; set; }
public double? quantity { get; set; }
public int? _delete_at { get; set; }
}
public class ProductItemObject
{
public List<ProductItem> product_items { get; set; }
}
A example on serializing :
List<ProductItem> list = new List<ProductItem>();
ProductItemObject o = new ProductItemObject { product_items = list };
var item1 = new ProductItem { _at = 1, product_id = "001" };
var item2 = new ProductItem { _at = 2, quantity = 2.00 };
var item3 = new ProductItem { _delete_at = 3 };
list.Add(item1);
list.Add(item2);
list.Add(item3);
string json = JsonConvert.SerializeObject(o, Formatting.Indented);
// json string :
// {
// "product_items": [
// {
// "_at": 1,
// "product_id": "001",
// "quantity": null,
// "_delete_at": null
// },
// {
// "_at": 2,
// "product_id": null,
// "quantity": 2.0,
// "_delete_at": null
// },
// {
// "_at": 0,
// "product_id": null,
// "quantity": null,
// "_delete_at": 3
// }
// ]
//}
An alternative full dynamic that gets u the same Json string without any model :
var jsonObject = new JObject();
dynamic objectList = jsonObject;
objectList.product_items = new JArray() as dynamic;
dynamic item = new JObject();
item._at = 1;
item.product_id = "999";
objectList.product_items.Add(item);
item = new JObject();
item._at = 2;
item.quantity = 2.00;
objectList.product_items.Add(item);
item = new JObject();
item._delete_at = 3;
objectList.product_items.Add(item);
string json = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObject, Formatting.Indented);

Well, if I understand you properly and you just need to be able to generate that json, the product list should be dynamic with maybe anonymous classes then:
public class Products
{
public Products()
{
product_items = new List<dynamic>();
}
public List<dynamic> product_items { get; set; }
}
products.product_items.Add(new { _at = 1, product_id = "999" });

Related

Mongodb C# Update element in an multiple array with multiple values

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));

How to save the Inventory in a JSONString in C#

so today I tried to create a class for my inventory and add items to it. I created 2 classes, one with my inventory: name,amount,slot and one with a list List<Inventory>. But it always showed exceptions with this code:
public class Inventory
{
public string name { get; set; }
public int amount { get; set; }
public int slot { get; set; }
}
public class InventoryList
{
public List<Inventory> invList = new List<Inventory>();
}
In my startup code i serialized it,which worked, but i tried to deserialize it, and it threw exceptions.
Inventory inventory = new Inventory() { name = "Burger", amount = 1, slot = 2 };
string jsonString = JsonSerializer.Serialize(inventory);
So first of all, when i try to get the items in the list i get this error:
What i want: I want a clear JSON-String, which i can deserialize in C#.
i want, that the list looks like this:
[
{
"name":"cheese",
"amount":5,
"slot":1,
},
{
"name":"Bread",
"amount":2,
"slot":4,
},
]
You basically want to serialize/deserialize a LIST of objects. Here's a working example:
Inventory inventory = new Inventory() { name = "cheese", amount = 5, slot = 1 };
Inventory inventory2 = new Inventory() { name = "Bread", amount = 2, slot = 4 };
var inventoryList = new List<Inventory>()
{
inventory,
inventory2
};
var options = new JsonSerializerOptions()
{
WriteIndented = true
};
string jsonString = JsonSerializer.Serialize(inventoryList, options);
Console.Write($"Serialized list {jsonString} {Environment.NewLine}");
var list = JsonSerializer.Deserialize<List<Inventory>>(jsonString);
Console.Write($"Deserialization completed");
Result:
The example above matches the JSON structure that you said you need.
If you still need an object wrapper it should work like this:
class Program
{
static void Main(string[] args)
{
Inventory inventory = new Inventory() { name = "cheese", amount = 5, slot = 1 };
Inventory inventory2 = new Inventory() { name = "Bread", amount = 2, slot = 4 };
var invList = new List<Inventory>()
{
inventory,
inventory2
};
InventoryList inventoryList = new InventoryList() {invList = invList };
var options = new JsonSerializerOptions()
{
WriteIndented = true
};
string jsonString = JsonSerializer.Serialize(inventoryList, options);
Console.Write($"Serialized list {Environment.NewLine} {jsonString} {Environment.NewLine}");
var list = JsonSerializer.Deserialize<InventoryList>(jsonString);
Console.Write($"Deserialization completed");
}
}
public class Inventory
{
public string name { get; set; }
public int amount { get; set; }
public int slot { get; set; }
}
public class InventoryList
{
public List<Inventory> invList { get; set; }
}
Note the change for invList. It's a get/set property now.
However, this wrapper will add another layer of curly brackets to your json:
Result:
You're trying to Deserialize Inventory type and assign the result object to InventoryList
You can learn from this sample (different json format)
public class Inventory
{
public string name { get; set; }
public int amount { get; set; }
public int slot { get; set; }
}
public class InventoryList
{
public List<Inventory> invList { get; set; }
}
//SAMPLE 1
InventoryList lInventory = new InventoryList()
{
invList = new List<Inventory>
{
new Inventory {name = "cheese", amount = 5, slot = 1 },
new Inventory {name = "Bread", amount = 2, slot = 4 }
}
};
//it will produce
//{"invList":[{"name":"cheese","amount":5,"slot":1},{"name":"Bread","amount":2,"slot":4}]}
string jsonString = JsonSerializer.Serialize(lInventory);
//How to deserialize
InventoryList inventoryList = (InventoryList)JsonSerializer.Deserialize<InventoryList>(jsonString);
//SAMPLE 2
List<Inventory> invList = new List<Inventory>
{
new Inventory {name = "cheese", amount = 5, slot = 1 },
new Inventory {name = "Bread", amount = 2, slot = 4 }
};
//it will produce
//[{"name":"cheese","amount":5,"slot":1},{"name":"Bread","amount":2,"slot":4}]
string jsonString2 = JsonSerializer.Serialize(invList);
//How to deserialize
List<Inventory> inventoryList2 = (List<Inventory>)JsonSerializer.Deserialize<List<Inventory>>(jsonString2);

How do i insert Adds many objects to the the List In c# MongoDB.Driver

How do I insert Adds many objects to the List In c# MongoDB.Driver?
my c# Entity
/// <summary>LogTest</summary>
public class VisitLog
{
/// <summary>MongoDB特有的字段</summary>
[MongoDB.Bson.Serialization.Attributes.BsonElement("_id")]
[JsonConverter(typeof(ObjectIdConverter))]
public MongoDB.Bson.ObjectId MongoId { get; set; }
/// <summary>YMD datetime</summary>
public int Yymmdd { get; set; }
/// <summary>Visitor</summary>
public string Visitor { get; set; }
/// <summary>VisitInfos</summary>
public List<VisitInfo> VisitInfos { get; set; }
}
In the MongoDBCode Like the code
// 1
{
"_id": ObjectId("5f506eb02000a9b52d72a600"),
"Yymmdd": NumberInt("20200903"),
"Visitor": "360spider",
"VisitInfos": [ ]
}
i will add objects to the "VisitInfos": [ ]
How do I insert Adds many objects to the List In c# MongoDB.Driver?
Way 1: insert only one object. my test code is:
var filter = Builders<VisitLog>.Filter.Eq("_id", item.MongoId);
var update = Builders<VisitLog>.Update.Push("VisitInfos", new VisitInfo { Visitor = Visitor, Browser = "IE", Ip = "192.168.1.1", Createtime = DateTime.Now.ToUnixTimeLocalIslong() });
var result = BB.UpdateOne(filter, update);
The Way 2: i want to insert InsertManyAsync
var items = BB.Find(x => x.Yymmdd.Equals(Yymmdd) && x.Visitor.Equals(Visitor)).Project<VisitLog>(fields).ToList();
if (items.Count > 0)
{
var item = items[0];
var VisitInfos = new List<VisitInfo>();
for (int j = 0; j < 10000; j++)
{
VisitInfos.Add(new VisitInfo { Visitor = Visitor, Browser = "IE", Ip = "192.168.1.1", Createtime = DateTime.Now.ToUnixTimeLocalIslong() });
}
var filter = Builders<VisitLog>.Filter.Eq("_id", item.MongoId);
var update = Builders<VisitLog>.Update.Push("VisitInfos", VisitInfos);
var result = BB.UpdateOne(filter, update);
}
the way 2 is failed.
please help me.
this very much.....
On the Builders<Order>.Update there's a PushEach which accepts an IEnumerable. This is equivalent to doing:
{ $push: { scores: { $each: [ 90, 92, 85 ] } } }
https://docs.mongodb.com/manual/reference/operator/update/push/#append-multiple-values-to-an-array
For simplicity here's an example of an order and order items.
In MongoDB we'll have:
> db.orders.find()
{ "_id" : ObjectId("5f50aef4d7d9f967d0322932"), "Items" : [ ] }
Then we'll execute the following C# Code.
var client = new MongoClient();
var db = client.GetDatabase("test");
var items = db.GetCollection<Order>("orders");
var filter = Builders<Order>.Filter.Empty;
var update = Builders<Order>.Update.PushEach(x => x.Items, new[]
{
new OrderItem{Name = "Order 1", Price = 10.1M},
new OrderItem{Name = "Order 2", Price = 20.2M}
});
await items.UpdateOneAsync(filter, update);
public class Order
{
public ObjectId Id { get; set; }
public List<OrderItem> Items { get; set; }
= new List<OrderItem>();
}
public class OrderItem
{
public string Name { get; set; }
public decimal Price { get; set; }
}
Now if we take a look at our document in MongoDB we'll have the 2 items added to our array
db.orders.find().pretty()
{
"_id" : ObjectId("5f50aef4d7d9f967d0322932"),
"Items" : [
{
"Name" : "Order 1",
"Price" : "10.1"
},
{
"Name" : "Order 2",
"Price" : "20.2"
}
]
}

Adding Fulfillment to Shopify orders

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);
}
}

Parsing JSON with JObject

I need to parse a JSON, I am already parsing the first part of the record but I am having a problem with a sub record. This is my code:
List<JToken> results = new List<JToken>();
List<JToken> results2 = new List<JToken>();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
results = JObject.Parse(result).SelectToken("record").ToList();
}
List<Record> users = new List<Record>();
foreach (JObject token in results)
{
Record user = new Record();
user.id = Int32.Parse(token["id"].ToString());
user.full_name = token["full_name"].ToString();
user.email = token["email"].ToString();
//role.RoleName = token.SelectToken("name").ToString();
}
That's working perfectly but I have issues parsin a string that's a bit deeper. This is the JSON:
{
"record": [
{
"id": 2,
"institution_id": 1,
"full_name": "",
"email": "",
"role_id": 2,
"created": "2015-01-13 01:18:52.370379",
"updated": "2015-01-22 23:58:44.103636",
"branch_id": 1,
"Branch_by_branch_id": {
"id": 1,
"institution_id": 1,
"branch_name": "Test Branch"
}
}
]
}
I want to get the "branch_name" inside Branch_by_branch_id. How can I access it with Jobject?
If your JSON is this
{
"record": [
{
"id": 26,
"full_name": "",
"email": "",
"branch_id": 1,
"Branch_by_branch_id": {
"id": 1,
"institution_id": 1,
"branch_name": "NAME"
}
}
]
}
Have classes like this:
public class BranchByBranchId
{
public int id { get; set; }
public int institution_id { get; set; }
public string branch_name { get; set; }
}
public class Record
{
public int id { get; set; }
public string full_name { get; set; }
public string email { get; set; }
public int branch_id { get; set; }
public BranchByBranchId Branch_by_branch_id { get; set; }
}
public class RootObject
{
public List<Record> record { get; set; }
}
Then parse it and retrieve the value like this.
var root = JsonConvert.DeserializeObject<RootObject>(json);
var branchName = root[0].Branch_by_branch_id.branch_name;
I always prefer to access my JSON objects like this, because I like having my objects as native C# classes. The classes were generated by json2csharp.

Categories

Resources