This question already has answers here:
Send JSON via POST in C# and Receive the JSON returned?
(4 answers)
Closed 1 year ago.
{
"name": "group1",
"userData": "user-provided data attached to the person group.",
"recognitionModel": "recognition_03"
}
If I need to pass the above body in a http client call how do I format that in C#?
Maybe you find your anwser here:
public void JsonStringExample()
{
string example1 = #"{
""name"": ""group1"",
""userData"": ""user-provided data attached to the person group."",
""recognitionModel"": ""recognition_03""
}";
string example2 = "{"
+ " \"name\": \"group1\","
+ " \"userData\": \"user-provided data attached to the person group.\","
+ " \"recognitionModel\": \"recognition_03\""
+ "}";
var stringBuilder = new StringBuilder();
stringBuilder.AppendLine("{");
stringBuilder.AppendLine(" \"name\": \"group1\",");
stringBuilder.AppendLine(" \"userData\": \"user-provided data attached to the person group.\",");
stringBuilder.AppendLine(" \"recognitionModel\": \"recognition_03\"");
stringBuilder.AppendLine("}");
string example3 = stringBuilder.ToString();
string exmaple4 = String.Join(
"\r\n",
new string[]
{
"{",
" \"name\": \"group1\",",
" \"userData\": \"user-provided data attached to the person group.\",",
" \"recognitionModel\": \"recognition_03\"",
"}"
}
);
}
Related
This question already has answers here:
Deserialize JSON with C#
(10 answers)
How can I deserialize JSON with C#?
(19 answers)
Closed 8 months ago.
I am looking for a way to convert the following manually typed JSON list to a List I can load, but still output the same format in C#, so in can be POSTed to a REST API.
var accs = #"{
" + "\n" +
#" ""Cities"": [
" + "\n" +
#" ""Atlanta"",
" + "\n" +
#" ""Chicago"",
" + "\n" +
#" ""San Diego""
" + "\n" +
#" ]
" + "\n" +
#"}
" + "\n" +
#"";
Assuming this is your model:
public class State
{
public List<string> Cities { get; set; }
public State(List<string> cities)
{
Cities = cities;
}
}
This is how you serialize and deserialize:
using System.Text.Json;
var listOfCities = new List<string>() { "Atlanta", "Chicago", "San Diego"};
var state = new State(listOfCities);
//Serialize
var jsonArray = JsonSerializer.Serialize(state);
// Deserialize
var obj = JsonSerializer.Deserialize<State>(jsonArray);
When you use #", you can avoid the + concatenation like:
var accs = #"
{
'Cities': [
'Atlanta',
'Chicago',
'San Diego'
]
}
";
You'll need to use ' (single quotes) instead of " in your JSON text, otherwise you have to escape \" them.
you don't need any custom classes, you can just parse your json string
using Newtonsoft.Json;
var jsonParsed=JObject.Parse(accs);
if you need list of cities as c# instance
List<string> cities =jsonParsed["Cities"].ToObject<List<string>>();
if you need just a well formatted json string
accs = jsonParsed.ToString();
result
{
"Cities": [
"Atlanta",
"Chicago",
"San Diego"
]
}
I'm trying to get a local c# program that I have to connect to GCP (Bigquery).
I have gotten a credentials json file from GCP which looks something like:
{
"type": "service_account",
"project_id": "project-id-1",
"private_key_id": "veryprivatekeything",
"private_key": "-----BEGIN PRIVATE KEY-----\nmany_letters_and_symbols_here\n-----END PRIVATE KEY-----\n",
"client_email": "bq-access-for-test#project-id-1.iam.gserviceaccount.com",
"client_id": "1234567891011",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/bq-access-for-test%40project-id-1.iam.gserviceaccount.com"
}
My code looks something like:
string path2key = "C:/Users/me/Downloads/project-id-1-letters.json";
byte[] jsonBytes = File.ReadAllBytes(path2key);
// I also tried another encoding but same deal
// string jsonString = Encoding.UTF32.GetString(jsonBytes);
string jsonString = File.ReadAllText(path2key);
Console.WriteLine(jsonString);
// This is where the error is
string jsonStringDeserialized = JsonConvert.DeserializeObject<string>(jsonString);
Console.WriteLine(jsonStringDeserialized);
// I presume I'm passing json as a string???
var credential = GoogleCredential.FromJson(jsonStringDeserialized);
if (credential.IsCreateScopedRequired)
{
credential = credential.CreateScoped(new[]
{
BigqueryService.Scope.Bigquery
});
}
Console.WriteLine("Credentials Created");
var client = BigQueryClient.Create("projectId", credential);
Console.WriteLine("Client Created");
var table = client.GetTable("bigquery-public-data", "samples", "shakespeare");
var sql =
$" SELECT corpus AS title" +
$" , COUNT(word) AS unique_words " +
$" FROM {table} " +
$" GROUP BY title " +
$" ORDER BY unique_words DESC " +
$" LIMIT 10"
;
var results = client.ExecuteQuery(sql, parameters: null);
foreach (var row in results)
{
Console.WriteLine($"{row["title"]}: {row["unique_words"]}");
}
However when I get to the line that tries to deserialize the jsonString it complains that
Newtonsoft.Json.JsonReaderException: 'Unexpected character encountered while parsing value: {. Path '', line 1, position 1.'
I'm assuming the json isn't malformed as it was downloaded directly from GCP and I've checked with linters that it's valid.
What's the next thing I should be trying?
you don' t need this code, it doesn' t create anything , except the error
string jsonStringDeserialized = JsonConvert.DeserializeObject<string>(jsonString);
Console.WriteLine(jsonStringDeserialized);
try just this
string jsonString = File.ReadAllText(path2key);
var credential = GoogleCredential.FromJson(jsonString);
.... your code
I am trying to construct a raw json string as below to send it out in http request
var requestContent = #"{
""name"": ""somename"",
""address"": ""someaddress""
}";
Instead of having name and address value hardcoded I was hoping to supply them from below variables
string name = "someName";
string address = "someAddress";
But the below does not work. Any idea ?
var requestContent = #"{
""name"": \" + name \",
""address"": \" + address \"
}";
The correct syntax is:
var requestContent = #"{
""name"": """ + name + #""",
""address"": """ + address + #"""
}";
Or, you could use string.Format:
var requestContent = string.Format(#"{
""name"": ""{0}"",
""address"": ""{1}""
}", name, address);
Or you could use an actual JSON serializer.
You could use a verbatim string together with interpolation as well:
var requestContent = $#"{{
""name"": ""{name}"",
""address"": ""{address}""
}}";
EDIT: For this to work you have to make sure that curly braces you want in the output are doubled up (just like the quotes). Also, first $, then #.
Instead use Newtonsoft.JSON JObject() like
dynamic myType = new JObject();
myType.name = "Elbow Grease";
myType.address = "someaddress";
Console.WriteLine(myType.ToString());
Will generate JSON string as
{
"name": "Elbow Grease",
"address": "someaddress"
}
This question already has answers here:
Escape double quotes in a string
(9 answers)
How can I add double quotes to a string that is inside a variable?
(20 answers)
Closed 7 years ago.
I have been looking at this for a while trying everything I can find on SO. There are many posts but I must be missing something.
I am building a string and need to get a double quote in it between two variables.
I want the string to be
convert -density 150 "L:\03 Supervisors\
The code is
tw.WriteLine(strPrefix + " " + strLastPath);
where
strPrefix = convert -density 150
and
strLastPath = L:\\03 Supervisors\
I have tried many combinations of "" """ """" \" "\ in the middle where the space is being inserted.
Please show me what I am missing.
You have two options:
var output1 = strPrefix + "\"" + strLastPath;
Or using a verbatim string:
var output2 = strPrefix + #"""" + strLastPath;
Here's a sample console application that achieves what you're after:
namespace DoubleQuote
{
class Program
{
static void Main(string[] args)
{
var strPrefix = "convert - density 150";
var strLastPath = #"L:\\03 Supervisors\";
Console.WriteLine(strPrefix + " \"" + strLastPath);
Console.ReadKey();
}
}
}
If written as a format string it would look like this:
var textToOutput = string.Format("{0} \"{1}", strPrefix, strLastPath);
Console.WriteLine(textToOutput);
Please try this
var strPrefix = "convert -density 150";
var strLastPath = #"L:\03 Supervisors\";
Console.WriteLine(strPrefix + " " + '"'+strLastPath);
I have the following code in C# that I'm able to attach to IE, and it runs through fine until I hit the JSON, which I receive a javascript error complaining about the syntax. How exactly should I escape javscript code within C# ?
string jsonStr = #"[
{ \'name\': \'Obj1\', \'description\': \'Test description...\', \'url\':\'http://www.test.com\' },
{ \'name\': \'Obj2\', \'description\': \'Testing...\', \'url\':\'http://www.test.com\' },
{ \'name\': \'Obj3\', \'description\': \'Welp...\', \'url\':\'http://www.test.com\' }
]";
IHTMLScriptElement scriptObject = (IHTMLScriptElement)document.createElement("script");
scriptObject.type = #"text/javascript";
scriptObject.text = #"function test() {
var Edit = 'document.getElementById(\'tTest\').innerHTML = \'<h2 class=\'label3\'><span>Foo</span></h2><ol class=\'container-list\'>';
var json = '" + jsonStr + #"';
$.each(json, function (index, x) {
Edit += '<li class=\'test1\'><h3><a href=\'#\'><b>' + x.name + '</b> 1</a></h3><div class=\'url\'><cite>' + x.url + '</cite></div><div class=\'creative\'>' + x.description + '</div></li>';
});
Edit += '</ol>\';
eval('Edit');
}";
((HTMLHeadElement)head).appendChild((IHTMLDOMNode)scriptObject);
IHTMLDocument2 doc = (IHTMLDocument2)this._webBrowser2.Document;
IHTMLWindow2 parentWindow = doc.parentWindow;
if (parentWindow != null)
parentWindow.execScript("test();", "javascript");
The c# code is fine, I'm just having trouble wrapping my head about injecting the javascript code with all the quotations, single quotes, etc to eliminate the javascript error. Any help is GREATLY appreciated!
When using verbatim string literals prefixed with #, it means that the enclosed string is treated as literal. So basically no backslash '\' escaping. To escape double quote ("), just double it ("").
string jsonStr = #"[
{""name"": ""Obj1"", ""description"": ""Test description..."", ""url"":""http://www.test.com"" },
{ ""name"": ""Obj2"", ""description"": ""Testing..."", ""url"":""http://www.test.com"" },
{ ""name"": ""Obj3"", ""description"": ""Welp..."", ""url"":""http://www.test.com"" }
]";