I called a REST API with the following JSON string returned:
"{\"profile\":[{\"name\":\"city\",\"rowCount\":1,\"location\": ............
I tried to remove escape character with the following code before I deserialize it:
jsonString = jsonString.Replace(#"\", " ");
But then when I deserialize it, it throws an input string was not in a correct format:
SearchRootObject obj = JsonConvert.DeserializeObject<SearchRootObject>(jsonString);
The following is the complete code:
public static SearchRootObject obj()
{
String url = Glare.searchUrl;
string jsonString = "";
// Create the web request
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
// Get response
var response = request.GetResponse();
Stream receiveStream = response.GetResponseStream();
// Pipes the stream to a higher level stream reader with the required encoding format.
StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
jsonString = jsonString + readStream.ReadToEnd();
jsonString = jsonString.Replace(#"\", " ");
// A C# object representation of deserialized JSON string
SearchRootObject obj = JsonConvert.DeserializeObject<SearchRootObject>(jsonString);
return obj;
}
After switching to use JavaScriptSerializer() to deserialize JSON string , I realized that I have an int type property in my object for a decimal value in the JSON string. I changed int to double, and this solved my problem. Both JsonConvert.DeserializeObject<> and JavaScriptSerializer() handle escape character. There's no need to remove escape character.
I replaced the following codes:
jsonString = jsonString.Replace(#"\", " ");
SearchRootObject obj = JsonConvert.DeserializeObject<SearchRootObject>(jsonString);
return obj;
With:
return new JavaScriptSerializer().Deserialize<SearchObj.RootObject>(jsonString);
Related
I'm working with rest delete API. It is working fine but its returning No Content in every success response. I have given too much time but problem is still persist. Could you please correct me where I am wrong with code. I searched and implemented same but I don't know at what point I am making mistake.
public static string DeleteMessage(String queueName, string popreceipt, string messageid)
{
string requestMethod = "DELETE";
String urlPath = String.Format("{0}/messages/{1}?popreceipt={2}", queueName, Uri.EscapeDataString(messageid), Uri.EscapeDataString(popreceipt));
String storageServiceVersion = "2017-11-09";
String dateInRfc1123Format = DateTime.UtcNow.ToString("R", CultureInfo.InvariantCulture);
String canonicalizedHeaders = String.Format(
"x-ms-date:{0}\nx-ms-version:{1}",
dateInRfc1123Format,
storageServiceVersion);
//String canonicalizedResource = String.Format("/{0}/{1}", StorageAccountName, urlPath);
String canonicalizedResource = string.Format("/{0}/{1}/messages/{2}\npopreceipt:{3}", StorageAccountName, queueName, messageid, popreceipt);
String stringToSign = String.Format(
"{0}\n\n\n\n\n\n\n\n\n\n\n\n{1}\n{2}",
requestMethod,
canonicalizedHeaders,
canonicalizedResource);
String authorizationHeader = CreateAuthorizationHeader(stringToSign);
Uri uri = new Uri("https://" + StorageAccountName + ".queue.azure.com/" + urlPath);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = requestMethod;
request.Headers.Add("x-ms-date", dateInRfc1123Format);
request.Headers.Add("x-ms-version", storageServiceVersion);
request.Headers.Add("Authorization", authorizationHeader);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
Stream dataStream = response.GetResponseStream();
return response.StatusCode.ToString();
}
}
public static String CreateAuthorizationHeader(String canonicalizedString)
{
String signature = String.Empty;
using (HMACSHA256 hmacSha256 = new HMACSHA256(Convert.FromBase64String(StorageAccountKey)))
{
Byte[] dataToHmac = System.Text.Encoding.UTF8.GetBytes(canonicalizedString);
signature = Convert.ToBase64String(hmacSha256.ComputeHash(dataToHmac));
}
String authorizationHeader = String.Format(
CultureInfo.InvariantCulture,
"{0} {1}:{2}",
"SharedKey",
StorageAccountName,
signature
);
return authorizationHeader;
}
This is expected behavior. Delete Message operation is supposed to return no content. From the documentation here:
Status code
A successful operation returns status code 204 (No
Content).
As an addition to Gaurav's answer: deleting a message is not the same as getting or dequeuing a message. What would you expect calling DELETE to return?
According to MDN (DELETE - responses):
If a DELETE method is successfully applied, there are several response status codes possible:
A 202 (Accepted) status code if the action will likely succeed but has not yet been enacted.
A 204 (No Content) status code if the action has been enacted and no further information is to be supplied.
A 200 (OK) status code if the action has been enacted and the response message includes a representation describing the status.
I want to edit an outbound payload using set-body in this way:
{"link": "http://localhost:7071/api"}
to
{"link":""} <- some other link
I have tried this but there is no change in outbound:
JObject inBody = context.Response.Body.As<JObject>();
string str = inBody.ToString();
var item = JObject.Parse("{ 'link': 'http://localhost:7071/api}");
item["link"] = "https://randomlink/269";
return str;
To explain why your code does not work:
JObject inBody = context.Response.Body.As<JObject>(); //Request
payload has been parsed and stored in `inBody` variable.
string str = inBody.ToString(); //`inBody` converted to string and stored in `str` variable.
var item = JObject.Parse("{ 'link': 'http://localhost:7071/api}"); //Some other JSON parsed and stored in `item` variable
item["link"] = "https://randomlink/269"; //`item` variable updated with new value
return str; //Returning `str` variable as new body value
You never actually change value of str to produce new body. Try:
JObject inBody = context.Response.Body.As<JObject>();
inBody["link"] = "https://randomlink/269";
return inBody.ToString();
I am using the sample code from the Unity website for the WWW class to make an API request but the text response is garbage. It looks like ����. When I log the response headers, I get a 200 response and everything seems ok except that the CONTENT-TYPE is image/jpeg. I have tried several different random .json files to test it out and they all return the same thing. Requesting an image to use as a texture does work.
public class SpeechReq : MonoBehaviour {
//public string url = "https://gist.githubusercontent.com/wethecode/1f79baf168680afb0f2d/raw/755f9fb71dcc34df811b4bc26448d88a0f97f34d/snippets.json";
public string url = "https://gist.githubusercontent.com/damienh/fea91ab710475d499a09/raw/893065428badd8bfdc7b39fe17675b8aa031ac51/gistfile1.json";
IEnumerator Start()
{
WWW www = new WWW(url);
yield return www;
string respText = www.text;
Debug.Log(respText);
//Output: ����
byte[] resp = www.bytes;
var str = System.Text.Encoding.Default.GetString(resp);
Debug.Log(str);
//Output: ÿØÿà
if (www.responseHeaders.Count > 0)
{
foreach (KeyValuePair<string, string> entry in www.responseHeaders)
{
Debug.Log(entry.Value + "=" + entry.Key);
//Output: HTTP/1.0 200 OK=STATUS
//...
//image/jpeg=CONTENT-TYPE
}
}
}
}
The WWW class's .text method returns the UTF8 Byte Order Mark at the beginning of the response by default. See a description of the BOM here
You could try:
string jsonText = "";
if (string.IsNullOrEmpty(www.error))
{
jsonText = System.Text.Encoding.UTF8.GetString(www.bytes, 3, www.bytes.Length - 3); // Skip the UTF8 BOM
JSONObject myObject = new JSONObject(jsonText);
}
MvcResult result;
result = this.mockMvc.perform(something).andExpect( status().isOk() ).andReturn();
String resultAsString = result.getResponse().getContentAsString();
/* resultAsString = "{"abc":"def","ghi":"jkl","mno":"pqr"}" */
String resultAsString1 = StringUtils.remove( resultAsString, "{" );
resultAsString1 = StringUtils.remove( resultAsString1, "}" );
Map<String, String> resultAsMap = Splitter.on( "," ).withKeyValueSeparator( ":" ).split( resultAsString1 );
String myValueName = (String) resultAsMap.get( "mno" );
But in debug mode, what I'm seeing is that myValueName = null.
Can someone please help?
I'm importing com.google.common.base.Splitter;
The keys in the input string are enclosed in quotes, but the key used for the map lookup isn't. You may want to use a JSON library instead, like Gson:
JsonObject obj = (JsonObject) (new JsonParser().parse("{\"key\": \"value\"}"));
String value = obj.get("key");
I am trying to connect to servicebus and getting data from it, it seems since I've got the token I must reuse it evertime I make a request what's wrong with this code?here is the error I've got at the last
line The remote server returned an error: (401) Unauthorized.
//sample usage string mydata1 = string.Format(Constants.myData, brfId);
public static readonly myData= "https://sdgsdg.servicebus.windows.net/sgsdg/gdgsg/{0}";
//sample usage - string agendaByBriefingDetailIdURI = string.Format(Constants.myData2 BriefingID, accessCode);
public static readonly string myData2= "https://sdgsg.servicebus.windows.net/sdg/dgsg/{0}/{1}";
string SCOPE = "http://lalalalala.servicebus.windows.net/";
string WRAP_PASSWORD = "lalalalalala"
string WRAP_USERNAME = "lalalala";
string ACS_NAMESPACE = "lalalalala";
WebClient client = new WebClient();
client.BaseAddress = string.Format("https://{0}.accesscontrol.windows.net", ACS_NAMESPACE);
NameValueCollection values = new NameValueCollection();
values.Add("wrap_name", WRAP_USERNAME);
values.Add("wrap_password", WRAP_PASSWORD);
values.Add("wrap_scope", SCOPE);
// WebClient takes care of the URL Encoding
byte[] responseBytes = client.UploadValues("WRAPv0.9", "POST", values);
// the raw response from ACS
string response = Encoding.UTF8.GetString(responseBytes);
string token = response.Split('&').Single(x => x.StartsWith("wrap_access_token=", StringComparison.OrdinalIgnoreCase)).Split('=')[1];
string decodedToken = HttpUtility.UrlDecode(token);
string.Format("WRAP access_token=\"{0}\"", HttpUtility.UrlDecode(token));
WebClient webClient = new WebClient();
webClient.Headers["Authorization"] = string.Format("WRAP access_token=\"{0}\"", HttpUtility.UrlDecode(token));
string returnString = webClient.DownloadString(string.Format(mystaticre, 10));