3

Good day,

I'm really new to programming and trying to play around APIs.

I saw this example from the API documentation

using (var content = new StringContent("{  \"orderNumber\": \"TEST-ORDER-API-DOCS\",  \"orderKey\": \"0f6bec18-3e89-4881-83aa-f392d84f4c74\",  \"orderDate\": \"2015-06-29T08:46:27.0000000\",  \"paymentDate\": \"2015-06-29T08:46:27.0000000\",  \"shipByDate\": \"2015-07-05T00:00:00.0000000\",  \"orderStatus\": \"awaiting_shipment\",  \"customerId\": 37701499,  \"customerUsername\": \"headhoncho@whitehouse.gov\",  \"customerEmail\": \"headhoncho@whitehouse.gov\",  \"billTo\": {    \"name\": \"The President\",    \"company\": null,    \"street1\": null,    \"street2\": null,    \"street3\": null,    \"city\": null,    \"state\": null,    \"postalCode\": null,    \"country\": null,    \"phone\": null,    \"residential\": null  },  \"shipTo\": {    \"name\": \"The President\",    \"company\": \"US Govt\",    \"street1\": \"1600 Pennsylvania Ave\",    \"street2\": \"Oval Office\",    \"street3\": null,    \"city\": \"Washington\",    \"state\": \"DC\",    \"postalCode\": \"20500\",    \"country\": \"US\",    \"phone\": \"555-555-5555\",    \"residential\": true  },  \"items\": [    {      \"lineItemKey\": \"vd08-MSLbtx\",      \"sku\": \"ABC123\",      \"name\": \"Test item #1\",      \"imageUrl\": null,      \"weight\": {        \"value\": 24,        \"units\": \"ounces\"      },      \"quantity\": 2,      \"unitPrice\": 99.99,      \"taxAmount\": 2.5,      \"shippingAmount\": 5,      \"warehouseLocation\": \"Aisle 1, Bin 7\",      \"options\": [        {          \"name\": \"Size\",          \"value\": \"Large\"        }      ],      \"productId\": 123456,      \"fulfillmentSku\": null,      \"adjustment\": false,      \"upc\": \"32-65-98\"    },    {      \"lineItemKey\": null,      \"sku\": \"DISCOUNT CODE\",      \"name\": \"10% OFF\",      \"imageUrl\": null,      \"weight\": {        \"value\": 0,        \"units\": \"ounces\"      },      \"quantity\": 1,      \"unitPrice\": -20.55,      \"taxAmount\": null,      \"shippingAmount\": null,      \"warehouseLocation\": null,      \"options\": [],      \"productId\": 123456,      \"fulfillmentSku\": \"SKU-Discount\",      \"adjustment\": true,      \"upc\": null    }  ],  \"amountPaid\": 218.73,  \"taxAmount\": 5,  \"shippingAmount\": 10,  \"customerNotes\": \"Thanks for ordering!\",  \"internalNotes\": \"Customer called and would like to upgrade shipping\",  \"gift\": true,  \"giftMessage\": \"Thank you!\",  \"paymentMethod\": \"Credit Card\",  \"requestedShippingService\": \"Priority Mail\",  \"carrierCode\": \"fedex\",  \"serviceCode\": \"fedex_2day\",  \"packageCode\": \"package\",  \"confirmation\": \"delivery\",  \"shipDate\": \"2015-07-02\",  \"weight\": {    \"value\": 25,    \"units\": \"ounces\"  },  \"dimensions\": {    \"units\": \"inches\",    \"length\": 7,    \"width\": 5,    \"height\": 6  },  \"insuranceOptions\": {    \"provider\": \"carrier\",    \"insureShipment\": true,    \"insuredValue\": 200  },  \"internationalOptions\": {    \"contents\": null,    \"customsItems\": null  },  \"advancedOptions\": {    \"warehouseId\": 98765,    \"nonMachinable\": false,    \"saturdayDelivery\": false,    \"containsAlcohol\": false,    \"mergedOrSplit\": false,    \"mergedIds\": [],    \"parentId\": null,    \"storeId\": 12345,    \"customField1\": \"Custom data that you can add to an order. See Custom Field #2 & #3 for more info!\",    \"customField2\": \"Per UI settings, this information can appear on some carrier's shipping labels. See link below\",    \"customField3\": \"https://help.shipstation.com/hc/en-us/articles/206639957\",    \"source\": \"Webstore\",    \"billToParty\": null,    \"billToAccount\": null,    \"billToPostalCode\": null,    \"billToCountryCode\": null  }}", System.Text.Encoding.Default, "application/json"))

This is really a stupid question but what I want to do is add variables to this string content. The problem is that I don't quite understand how to read or how this string is formatted (Specifically the "\"). I usually add @ in a string if I need to add "\" so I'm not sure if the "\" should be included in the string in some parts or that is used in this example to concat.

Can someone help how I can add variables to this string content?

Thank you for the help!

Raymond
  • 35
  • 1
  • 5
  • 1
    Welcome to StackoverFlow. Please [take the tour](https://stackoverflow.com/tour), read about [how to ask good questions](https://stackoverflow.com/help/how-to-ask) and learn about [how to create a Minimal, Complete and Verifiable Example](https://stackoverflow.com/help/mcve). – Gaurang Dave Apr 25 '18 at 02:05

4 Answers4

3

From MSDN

Provides HTTP content based on a string.

Very basic use of StringContent is to send data to server while accessing any API.

Here I am taking a simple example of Login API in a system.

// Following is the key value pairs (data) which we need to send to server via API.
Dictionary<string, string> jsonValues = new Dictionary<string, string>();
jsonValues.Add("username", "testuser");
jsonValues.Add("password", "XXXXXXXXXX"); // better to encrypt passwod before sending to API.

HttpClient client = new HttpClient();

// Used Newtonsoft.Json library to convert object to json string. It is available in Nuget package.
StringContent sc = new StringContent(JsonConvert.SerializeObject(jsonValues), UnicodeEncoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(webAddress, sc);

string content = await response.Content.ReadAsStringAsync();
Console.WriteLine("Result: " + content);

Check this SO post for some other explanation from other users.

Gaurang Dave
  • 3,956
  • 2
  • 15
  • 34
0

You can not use "\" character in your content like that, You have to convert your content to Base64 stream and revert it back to your plan content at the destination, You can find the full explanation and the codes in this answer:

https://stackoverflow.com/a/13938317/4189817

Mohammad Nikravesh
  • 947
  • 1
  • 8
  • 27
0

To answer your other question, @ before a string means it is a string literal, and everything you type will be in the string verbatim.

in a string variable, some characters have to be "escaped", and \ is the escape character.

to get a double quote, you have to type \"

to put a single \ in, you type two backslashes

newline is \n

tab is \t

Chris H
  • 932
  • 4
  • 8
-1
StringContent sc = new StringContent("{\"title\":\"" + yourStringVariable + "\"}");
4b0
  • 21,981
  • 30
  • 95
  • 142
  • 3
    While this code may solve the question, [including an explanation](https://meta.stackoverflow.com/questions/392712/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion – Muhammad Dyas Yaskur May 19 '20 at 22:39
  • Also use proper formatting when posting code samples. – richardev May 20 '20 at 00:04