Adding Fulfillment to Shopify orders - c#

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

Related

How to get value of a key by referencing another key in the same JSON?? Also how to add string to the end of uri?

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

Add value in json in each records

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

How to use Linq add list data to list sub class?

i want add list data (from class) to sub class list for sent JSON FORMAT to other api.
Class
public class InPaymentDetailResponse
{
public List<InPaymentDetail> Data { get; set; }
}
public class InPaymentDetail
{
public string runningno { get; set; }
public decimal totalpremium { get; set; }
}
public class InformationRequest
{
.....
.....
public List<CreateDetailRequest> _detailData { get; set; }
public ExPaymentRequest _payment { get; set; }
}
public class ExPaymentRequest
{
.....
.....
public ExCashtransaction _cash { get; set; }
}
public class ExCashtransaction
{
public string createby { get; set; }
public DateTime createdate { get; set; }
public List<ExCashtransactionDetailsRequest> details { get; set; }
}
public class ExCashtransactionDetailsRequest
{
public string runningno { get; set; }
public decimal amount { get; set; }
}
Code C#
private async Task<.....> CreateInfo(InformationRequest r)
{
InPaymentDetailResponse resPaymentDetail = new InPaymentDetailResponse();
resPaymentDetail.Data = new List<InPaymentDetail>();
foreach (var item in r._detailData)
{
.....
..... //Process Data
.....
var resPaymentDetailData = new InPaymentDetail
{
//Add List Data To New Object
runningno = item.runningno,
totalpremium = item.totalpremium
};
resPaymentDetail.Data.Add(resPaymentDetailData);
}
HttpResponseMessage response = new HttpResponseMessage();
foreach (var res in resPaymentDetail.Data.ToList())
{
//i want add
//req._payment._cash.details.runningno = res.runningno //Ex. 10
//req._payment._cash.details.amount = res.amount //Ex. 99.9
//next loop
//req._payment._cash.details.runningno = res.runningno //Ex. 20
//req._payment._cash.details.amount = res.amount //Ex. 23.2
}
//sent to other api
response = await client.PostAsJsonAsync("", req._payment._cash);
.....
.....
}
i want result code when add list data to req._payment._cash:
(because to use it next process)
"createby": "system",
"createdate": 26/09/2018",
"details": [
{
"runningno": "10", //before add data to list is null
"amount": 99.9 //before add data to list is null
},
{
"runningno": "20", //before add data to list is null
"amount": 23.2 //before add data to list is null
}
]
Help me please. Thanks in advance.
List<ExCashtransactionDetailsRequest> detailsObj = new List<ExCashtransactionDetailsRequest>();
foreach (var res in resPaymentDetail.Data.ToList())
{
detailsObj.Add(new ExCashtransactionDetailsRequest(){ runningno =res.runningno, amount = res.amount });
}
and finally, add details object to your property
req._payment._cash.details = detailsObj;

How to Convert List<T> to BsonArray to save a MongoDB Document

I'm having an Model Class, I need to Save it in a MongoDB Collection.
My Model Class:
public Class Employee
{
public string EmpID { get; set; }
public string EmpName { get; set; }
public List<Mobile> EmpMobile { get; set; }
}
public Class Mobile
{
public string MobID { get; set; }
public string MobNumber { get; set; }
public bool IsPreferred { get; set; }
}
The Values are
Employee EmpInfo = new Employee()
{
EmpID = "100",
EmpName = "John",
EmpMobile = new List<Mobile>()
{
{ MobNumber = "55566610", IsPreferred = true },
{ MobNumber = "55566611", IsPreferred = false },
}
}
BsonDocument _employee = new BsonDocument()
{
{ "Emp_ID", EmpInfo.EmpID },
{ "Emp_Name", EmpInfo.EmpName },
{ "Emp_Mobile", new BsonArray (EmpInfo.EmpMobile.Select(m => new
{
MobID = new ObjectId(),
MobNumber = m.MobNumber,
IsPreferred = m.IsPreferred
})) }
};
var collection = _database.GetCollection<BsonDocument>("EmployeeInfo");
collection.InsertOne(_employee);
I wish to save the above EmpInfo of type Employee in a MongoDB. But I can't able to create a BsonDocument. Kindly assist me is there is anything wrong in the above code. If yes kindly assist me.
there is no need to serialize to bson document
You can use TYPED collection and just insert data
Please see attached code snipet with updated class structure
void Main()
{
// To directly connect to a single MongoDB server
// or use a connection string
var client = new MongoClient("mongodb://localhost:27017");
var database = client.GetDatabase("test");
var collectionEmpInfo = database.GetCollection<Employee>("Employee");
Employee EmpInfo = new Employee
{
EmpID = "100",
EmpName = "John",
EmpMobile = new List<Mobile>
{
new Mobile{ MobNumber = "55566610", IsPreferred = true, MobID = ObjectId.GenerateNewId() },
new Mobile{ MobNumber = "55566611", IsPreferred = false, MobID = ObjectId.GenerateNewId() },
}
};
collectionEmpInfo.InsertOne(EmpInfo);
var empList = collectionEmpInfo.Find(new BsonDocument()).ToList();
empList.Dump(); //dump is used in linqPad
}
public class Employee
{
public ObjectId Id { get; set; }
public string EmpID { get; set; }
public string EmpName { get; set; }
public List<Mobile> EmpMobile { get; set; }
}
public class Mobile
{
public ObjectId MobID { get; set; }
public string MobNumber { get; set; }
public bool IsPreferred { get; set; }
}
In addition to answer above, I can suggest following code if you want to deal directly with Bson for some reason:
BsonDocument _employee = new BsonDocument()
{
{ "Emp_ID", EmpInfo.EmpID },
{ "Emp_Name", EmpInfo.EmpName },
{ "Emp_Mobile", BsonArray.Create(EmpInfo.EmpMobile.Select(m => new BsonDocument()
{
{ "MobID" , new ObjectId() },
{ "MobNumber", m.MobNumber },
{ "IsPreferred", m.IsPreferred }
})) }
};
The reason of the error you've got is that BsonArray.Create creates an array of values, not an array of objects. See this question for details.

How to Get Values from a json response string in C#

I want to get "id" "gender", "name", "picture" from a this json response string
{
"data": [{
"name": "XXX",
"gender": "male",
"id": "528814",
"picture": {
"data": {
"is_silhouette": false,
"url": "https:\/\/fbcdn-profile-a.akamaihd.net\/hprofile-ak-frc3\/v\/t1.0-1\/p50x50\/551182_10152227358459008__n.jpg?oh=983b70686285c2f60f71e665ace8ed5f&oe=54C1220C&__gda__=1422017140_998fbe013c4fe191ccadfdbc77693a76"
}
}
}
string[] data = friendsData.Split(new string[] { "}," }, StringSplitOptions.RemoveEmptyEntries).ToArray();
foreach (string d in data)
{
try
{
FacebookFriend f = new FacebookFriend
{
id = d.Substring("\"id\":\"", "\""),
gender = d.Substring("gender\":\"", "\""),
name = d.Substring("name\":\"", "\""),
picture = d.Substring("\"picture\":{\"data\":{\"url\":\"", "\"").Replace(#"\", string.Empty)
};
FacebookFriendList.Add(f);
}
catch
{
continue;
}
}
This code looks bad if the json data changes then you need to modify your logic accordingly. I would suggest you to serialize and deserialize the model data using Json serialization.
Model:
public class SerializationModel
{
public Data Data { get; set; }
}
public class Data
{
public string Name { get; set; }
public string Gender { get; set; }
public string Id { get; set; }
public Picture Picture { get; set; }
}
public class Picture
{
public PictureData Data { get; set; }
}
public class PictureData
{
public bool is_silhouette { get; set; }
public string url { get; set; }
}
Serialize your data to get the json output is like,
SerializationModel serializationModel = new SerializationModel
{
Data = new Data
{
Gender = "mALE",
Id = "88",
Name = "User",
Picture = new Picture
{
Data = new PictureData
{
is_silhouette = true,
url = "www.google.com"
}
}
}
};
string serializedString = Newtonsoft.Json.JsonConvert.SerializeObject(serializationModel);
which would yield the below result,
{"Data":{"Name":"User","Gender":"mALE","Id":"88","Picture":{"Data":{"is_silhouette":true,"url":"www.google.com"}}}}
To deserialize the json data back to the model,
SerializationModel sm = Newtonsoft.Json.JsonConvert.DeserializeObject<SerializationModel>(serializedString);
Then you can get the required values from the model itself.

Categories

Resources