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"
}
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
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\"",
"}"
}
);
}
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"" }
]";
I have problem with deserialization of json string, because string is bad format.
For example json object consist string property statusMessage with value "Hello "dog" ".
The correct format should be "Hello \" dog \" " .
I would like remove double quotes from this property.
Something Like this. "Hello "dog" ". -> "Hello dog ".
Here is it original json string which I work.
"{\"jancl\":{\"idUser\":18438201,\"nick\":\"JANCl\",\"photo\":\"1\",\"sex\":1,\"photoAlbums\":1,\"videoAlbums\":0,\"sefNick\":\"jancl\",\"profilPercent\":75,\"emphasis\":false,\"age\":\"-\",\"isBlocked\":false,\"PHOTO\":{\"normal\":\"http://u.aimg.sk/fotky/1843/82/n_18438201.jpg?v=1\",\"medium\":\"http://u.aimg.sk/fotky/1843/82/m_18438201.jpg?v=1\",\"24x24\":\"http://u.aimg.sk/fotky/1843/82/s_18438201.jpg?v=1\"},\"PLUS\":{\"active\":false,\"activeTo\":\"0000-00-00\"},\"LOCATION\":{\"idRegion\":\"6\",\"regionName\":\"Trenčiansky kraj\",\"idCity\":\"138\",\"cityName\":\"Trenčianske Teplice\"},\"STATUS\":{\"isLoged\":true,\"isChating\":false,\"idChat\":0,\"roomName\":\"\",\"lastLogin\":1294925369},\"PROJECT_STATUS\":{\"photoAlbums\":1,\"photoAlbumsFavs\":0,\"videoAlbums\":0,\"videoAlbumsFavs\":0,\"videoAlbumsExts\":0,\"blogPosts\":0,\"emailNew\":0,\"postaNew\":0,\"clubInvitations\":0,\"dashboardItems\":1},\"STATUS_MESSAGE\":{\"statusMessage\":\"\"Status\"\",\"addTime\":\"1294872330\"},\"isFriend\":false,\"isIamFriend\":false}}"
Problem is here, json string consist this object:
"STATUS_MESSAGE": {"statusMessage":" "some "bad" value" ", "addTime" :"1294872330"}
Condition of string which I want modified:
string start with "statusMessage":"
string can has any *lenght from 0 -N *
string end with ", "addTime
So I try write pattern for string which start with "statusMessage":", has any lenght and is ended with ", "addTime.
Here is it:
const string pattern = " \" statusMessage \" : \" .*? \",\"addTime\" ";
var regex = new Regex(pattern, RegexOptions.IgnoreCase);
//here i would replace " with empty string
string result = regex.Replace(jsonString, match => ???);
But I think pattern is wrong, also I don’t know how replace double quotes with empty string (remove double quotes).
My goal is :
"statusMessage":" "some "bad" value"
to "statusMessage":" "some bad value"
Thank for advice
To serialize json on client side I use something like this:
var JSON = JSON || {};
JSON.stringify = JSON.stringify || function (obj) {
var t = typeof (obj);
if (t != "object" || obj === null) {
// simple data type
if (t == "string") obj = '"' + obj + '"';
return String(obj);
}
else {
// recurse array or object
var n, v, json = [], arr = (obj && obj.constructor == Array);
for (n in obj) {
v = obj[n]; t = typeof (v);
if (t == "string") v = '"' + v + '"';
else if (t == "object" && v !== null) v = JSON.stringify(v);
json.push((arr ? "" : '"' + n + '":') + String(v));
}
return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
}
};
then
$.ajax({
...
data: JSON.stringify({
someThing1: [
{ Id: '001', FooValue: ''},
{ Id: '002', FooValue: ''}
],
someThing2: [
{ Id: '001', FooValue: ''},
{ Id: '002', FooValue: ''}
]
}),
...
});
On server-side I use Newton.Json ( http://james.newtonking.com/pages/json-net.aspx )
object deserializeObject = JsonConvert.DeserializeObject(requestParameterTextRepresentation, RootType);
If you have no ability to modify client-side script to pass correct json-string, then all your regexps are vain effort.
This should do it:
var str = '"STATUS_MESSAGE": {"statusMessage":" "some "bad" value" ", "addTime" :"1294872330"}"';
str = str.replace(/("statusMessage"\s*:\s*")(.+?)("\s*,\s*"addTime)/, function(m0,m1,m2,m3) { return m1 + m2.replace(/"/g,'') + m3; });
//now str == "STATUS_MESSAGE": {"statusMessage":" some bad value ", "addTime" :"1294872330"}"
Edit: sorry i don't know why i confused this with a javascript question :s - You are able to do a very similar approach in c# tho i can't come up with the syntax right now.
While it is an extremely weak, hacky, solution, this should work in simple cases:
string pattern = #"(?<=""statusMessage"":"").*?(?="",""addTime"")";
string result = Regex.Replace(malformedJSON, pattern,
match => match.Value.Replace("\"", ""));
I'm using lookarounds to find the string, and then remove all quotes from it. You may also escape them by replacing with "\\\"".
Try This (Not a perfect solution though):
string data = "\"STATUS_MESSAGE\": {\"statusMessage\":\" \"some \"bad\" value\" \", \"addTime\" :\"1294872330\"}";
Regex rxStatusMessage = new Regex("\\s*\"statusMessage\"\\s*:\"\\s*");
Regex rxAddTime = new Regex("\",\\s*\"addTime\"\\s*:");
data = rxStatusMessage.Replace(data, "\x02");
data = rxAddTime.Replace(data, "\x03");
Regex rxReplace = new Regex("\x02.*\x03");
data = rxReplace.Replace(data, m => m.Value.Replace("\"", ""));
data = data.Replace("\x02", "\"statusMessage\":\"");
data = data.Replace("\x03", "\", \"addTime\" :");