Part of a public class I have builds a data structure for dataTables plugin.
The code to build the data structure is:
var response = "{ \"data\": [";
response = response + "[";
response = response + "\"Clark, Keith\",";
response = response + "\"Corporate\",";
response = response + "\"XXX-XXX-XXXX\",";
response = response + "\"XXX-XXX-XXXX\",";
response = response + "\"XXXX#XXXX.com\"";
response = response + "],";
response = response + "[";
response = response + "\"Clark, Keith\",";
response = response + "\"Corporate\",";
response = response + "\"YYY-YYY-YYYY\",";
response = response + "\"YYY-YYY-YYYY\",";
response = response + "\"YYYY#XXXX.com\"";
response = response + "]";
response = response + "] }";
return response;
This runs fine and creates the table as expected. Where I am running into issues is when I try to add HTML markup to a field. I want to use a font awesome icon next to the name to indicate status like this:
<i class="fa fa-arrow-up" style="color: #00ff00;" aria-hidden="true">
I have tried modifying my code to read:
response = response + "\"<i class=\"\"fa fa-arrow-up\"\" style=\"\"color: #00ff00;\"\" aria-hidden=\"\"true\"\">Clark, Keith\",";
But now I am receiving an error that the JSON is not properly formatted. Am I missing something or can HTML markup not be used inside a JSON structure?
The problem is that you're generating an invalid json string literal.
"<i class=""fa fa-arrow-up"" style=""color: #00ff00;"" aria-hidden=""true"">Clark, Keith",
Quotes are escaped using literal backslashes, not doubling them.
You would have had to do this instead:
"\"<i class=\\\"fa fa-arrow-up\\\" style=\\\"color: #00ff00;\\\" aria-hidden=\\\"true\\\">Clark, Keith\","
This demonstrates why exactly you shouldn't be generating strings like this. There are tools out there that can do this for you and safely, use them. Json.net will make easy work out of this.
var markup = "<i class=\"fa fa-arrow-up\" style=\"color: #00ff00;\" aria-hidden=\"true\">";
var response = new JObject
{
["data"] = new JArray
{
new JArray
{
markup + "Clark, Keith",
"Corporate",
"XXX-XXX-XXXX",
"XXX-XXX-XXXX",
"XXXX#XXXX.com",
},
new JArray
{
markup + "Clark, Keith",
"Corporate",
"YYY-YYY-YYYY",
"YYY-YYY-YYYY",
"YYYY#XXXX.com",
},
}
};
return response.ToString();
With that said, you shouldn't be adding markup to your data. Data is data and nothing more. If you want to affect how it is displayed, that markup should be added to your view.
Related
I'm trying to use RestSharp to POST some data, however I'm encountering an error with my JSON content in the IRestResponse response.
Error:
"{"status":"error","message":"Invalid input JSON on line 1, column 96: Unexpected character ('e' (code 101)): was expecting comma to separate Object entries",...}"
From the message I assume I'm missing a comma at the end of the "content" line to separate the objects but can't figure out how to do it? Or do I need to place my name/value pairs into their own objects?
var client = new RestClient("https://api.com/APIKEY");
var request = new RestRequest(Method.POST);
request.AddHeader("accept", "application/json");
request.AddHeader("content-type", "application/json");
request.AddParameter("application/json", "{\"properties\":{" +
"\"pipeline\":\"0\"," +
"\"content\":\"<b>Email: </b>\"" + user.Email + "\"<br/><b>Error: </b>\"" + string.Join("<br/>", type.Name.Split(',').ToList()) + "\"<br/><b>UserId: </b>\"" + user.userId + "\"<br/><b>RequestId: </b>\"" + callbackData.idReference +
"\"subject\":\"Error for\"" + user.FirstName + " " + user.LastName +
"\"owner_id\":\"001\"}}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
You should never manually build your own JSON! You should use an (anonymous) object and a dedicated JSON serialiser like Json.Net.
That being said RestSharp allows you to specify an object as the parameter value for AddParameter but you should probably be using AddJsonBody for the request body.
There are several mistakes in your manual JSON generation like missing quotes and commas at the end of the "content" and "subject" lines.
var client = new RestClient("https://api.com/APIKEY");
var request = new RestRequest(Method.POST);
request.AddHeader("accept", "application/json");
request.AddHeader("content-type", "application/json");
var parameter = new
{
properties = new {
pipeline = "0",
content = $"<b>Email: </b>\"{user.Email}\"<br/><b>Error: </b>\"{string.Join("<br/>", type.Name.Split(',').ToList())}\"<br/><b>UserId: </b>\"{user.userId}\"<br/><b>RequestId: </b>\"{callbackData.idReference}",
subject = $"Error for \"{user.FirstName} {user.LastName}\"",
owner_id = "001"
}
};
request.AddJsonBody(parameter)
IRestResponse response = client.Execute(request);
Doing it this way is much less error prone.
I want to sent a base64pdf, via http put.
Unfortunatly I get the 400 bad request error.
I tried it with the google rest api and there it worked fine.
string finalURL = upURL + pdf.Id + "/signedpdf";
string json = "{ 'base64Pdf' : '" + pdf.Base64Pdf + "' }";
using (var client = new HttpClient())
{
var response = await client.PutAsync(finalURL, new StringContent(json, Encoding.UTF8, "application/json"));
if (response.IsSuccessStatusCode)
return true;
}
It works when I create the Json by Javascriptserializer.
TransferObject to = new TransferObject(pdf.Base64Pdf);
var json2 = new JavaScriptSerializer().Serialize(to);
I believe the JSON standard only supports double quote characters. Your code is using single quote characters in your concatenated JSON. Base64 encoded string will not contain double quote characters so you should be good there. Try this:
string json = "{ \"base64Pdf\" : \"" + pdf.Base64Pdf + "\" }";
I'm making a web-app that needs data through an API. I am trying to re-purpose some of the developer's example code of a different function than the original code was written for. Here's the important part:
WebRequest request = WebRequest.Create(urlPrefix + "getthingjson/" + Key);
WebResponse response = request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
reader.Close();
response.Close();
// Parse returned JSON into data
//
using (var web = new WebClient())
{
web.Encoding = System.Text.Encoding.UTF8;
var jsonString = responseFromServer;
var jss = new JavaScriptSerializer();
var ThingsList = jss.Deserialize<List<Things>>(jsonString);
string ThingsListStr = "";
foreach (Things x in ThingsList)
ThingsListStr = ThingsListStr + ", " + x.Name;
MessageBox.Show(ThingsListStr);
}
I know that I need to change 'Name' in order to get a different piece of info on the 'Things' call. The thing is, I need to call results on a different function, instead of 'Things' say 'Details'. I don't know what to look for in place of 'Name' since when I search that it returns nothing. How could I just deserialize all of what JSON returns? Sorry if my terminology was off or I made a simple mistake, I'm new to JSON and C#. Thanks!
To get Details instead of Name property you should:
Check if you receive this data in json.
Adjust your c# class with Details property if it doesn't exist. (Go to Things class and add new Details property)
Change
ThingsListStr = ThingsListStr + ", " + x.Name;
to
ThingsListStr = ThingsListStr + ", " + x.Details;
I'm not very good with any networking type of things (as far as C# goes) but I need to post data (not get!) to a web url and then return what it outputs.
So far I'm using this for post and determining if it's logged in or not.
//credentials
string username = textBox1.Text;
string password = textBox2.Text;
using (WebClient client = new WebClient())
{
byte[] data = Encoding.Default.GetBytes("username="+username+"&password="+password);
client.Headers["Content-Type"] = "application/Json";
try
{
var response2 = client.UploadData(base_url + "/users/authenticate", "POST", data);
MessageBox.Show(Encoding.Default.GetString(response2));
}
catch { }
}
Note: Error I'm getting is 400 bad request. Any ideas?
Looking at the vine code, I would say you need to send it JSON data instead of URL data. With something simple like that you can just write the string.
String jsonData = "{\"username\": \"" + username + "\", \"password\": \"" + password + "\"}";
Updated to add encoding and be more strict with JSON data
PHP's JSON decoder wants UTF-8 encoded data, so also change the encoding line to
byte[] data = Encoding.UTF8.GetBytes(jsonData);
I have the following curl code:
curl 'localhost:8983/solr/sessions/update?commit=true' -H 'Content-type:application/json' -d '[{"Session_SessionId":"da7007e9-fe7a-4bdf-b9e4-1a55034cf08f","Session_HasComments":{"set":true}}]'
I am trying to convert to C#, but I am getting an error every time so unsure if my code is correct...
Here's what I have so far:
string path = "http://localhost:8983/solr/sessions/update?commit=true";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(path);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"Session_SessionId\":\"" + sessionId + "\"," +
"\"" + fieldName + "\":{\"set\":\"" + fieldValue + "\"}}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
It always seems to error () on this line:
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
The error i get is:
The remote server returned an error: (400) Bad Request.","StackTrace":" at System.Net.HttpWebRequest.GetResponse()
Any ideas? Thanks in advance!
Dave
Maybe it's that you have removed square brackets in your JSON content that you are streaming into request? Try adding the [ ] back to the start/end of data. Although the "BadRequest" is usually quite strict error that tells you that your HTTP request is malformed, your server may actually return that code also for other cases - like missing session id - which probably occurred here.
note the diff:
-d '[{"Session_SessionId":"da70.....
^ bracket
and
string json = "{\"Session_SessionId\":\"" + sessionId + "\"," + ....
^ no bracket
and the same at the end of data.
But, of course, that's just a guess. :)
Your request cannot be understood by the server. Did you check the output of json variable. I believe the JSON string is not generating properly.
Why don't you use JavaScriptSerializer.Serialize to create JSON string.
Your use the Update Handler with a JSON object will need to follow the JSON format outlined in Update JSON - Update Commands
As another user has suggested your JSON output does not match the CURL. Try the following rather than typing the text.
var data = new[]
{
new
{
Session_SessionId = "da7007e9-fe7a-4bdf-b9e4-1a55034cf08f",
Session_HasComments = new {set = true}
}
};
var json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(data);
Also, you are using the using keyword to write the data through, and attempt to handle response while inside the block - it probably does make a difference but it might be worth moving this outside this block.
Lastly, you may need to encode the data as a byte array.
Here is the code implementing the above suggestions.
string path = "http://localhost:8983/solr/sessions/update?commit=true";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(path);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
var data = new[]
{
new
{
Session_SessionId = "da7007e9-fe7a-4bdf-b9e4-1a55034cf08f",
Session_HasComments = new {set = true}
}
};
string json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(data);
byte[] byteData = new System.Text.ASCIIEncoding().GetBytes(json);
httpWebRequest.ContentLength = byteData.Length;
using (Stream stream = httpWebRequest.GetRequestStream())
{
stream.Write(byteData,0,byteData.Length);
}
HttpWebResponse resp = (HttpWebResponse)httpWebRequest.GetResponse();
string respStr = new StreamReader(resp.GetResponseStream()).ReadToEnd();
Console.WriteLine("Response : " + respStr);
Just use SolrNet. If you are doing this with Solr 4+, you need to download latest code and built it yourself, but that's very easy.
Dave, it worked for me.
You were missing square brackets. Just replace respective line with below:
string json = "[{\"Session_SessionId\":\"" + sessionId + "\"," +
"\"" + fieldName + "\":{\"set\":\"" + fieldValue + "\"}}]";