我想定位这个字符串类型" application / json"用于城市飞艇api。你能帮我解决我的字符串和结构错误吗?
string postData = "{"audience":"all","device_types":["android"],"notification":{"alert":"This is a broadcast."}}";
我确实尝试过添加斜杠" \"以下示例:
string postData = "{\"audience\":\"all\",\"device_types\":[\"android\"],\"notification\":{\"alert\":\"This is a broadcast.\"}}";
以下是我的完整代码:
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create("https://go.urbanairship.com/api/push/");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = "{'audience':'all','device_types':'['android']','notification': {'alert':'This is a broadcast.'}";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/json";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
//Do a http basic authentication somehow
string username = "Zx5EPSG7Qhu-BvYtz0laTg";
string password = "sIaj2CjASlm27pimHqOfhA";
string usernamePassword = username + ":" + password;
CredentialCache mycache = new CredentialCache();
mycache.Add(new Uri("https://go.urbanairship.com/api/push/"), "Basic", new NetworkCredential(username, password));
request.Credentials = mycache;
request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
我得到以下错误:
400 Bad Request – The request body was invalid, either due to malformed JSON or a data validation error. See the response body for more detail.
答案 0 :(得分:0)
第一个值中包含小类型,'
后有一个额外的 "all"
符号:
{
"audience": "all"',
"device_types": [
"android"
],
"notification": {
"alert": "This is a broadcast."
}
}
将来,您可以使用在线验证程序来处理此类情况,例如JSONLint。
答案 1 :(得分:0)
这应该有效:
{
"audience" : "all",
"device_types" : ["android"],
"notification" : {
"alert" : "This is a broadcast."
}
}