heres my JSON
var postData =
"{ \"registration_ids\": [ \"" + pushNotificationState.RegistrationId + "\" ], "+
"\"data\": {\""+ pushNotificationState.NotificationData.NotificationData + "\"}";
registration Id and notification data are variables. I'm getting a 400 response from the GCM sever saying JSON is incorrect format. Can anyone pick where I have gone wrong?
Cheers
You have one open { but have two close }.
var postData = "{ \"registration_ids\": [ \"" + pushNotificationState.RegistrationId + "\" ], " + "\"data\": \""+ pushNotificationState.NotificationData.NotificationData + "\"}";
Use some Json tools, instead of creating your string by hand. Otherwise you'd have problems if some of string variables contain {,}," etc.
var json = JsonConvert.DeserializeObject(
new {
registration_ids = new[] { pushNotificationState.RegistrationId },
data = pushNotificationState.NotificationData.NotificationData
});
var postData = "{ \"registration_ids\": [ \"" + pushNotificationState.RegistrationId + "\" ]}, "+
"\"data\": {\""+ pushNotificationState.NotificationData.NotificationData + "\"}";
Try replacing it with that.
You can use the below code to create the request object, then convert to json.
public class GCMRequest
{
public GCMRequest()
{
data = new PayLoad();
}
public List<string> registration_ids;
public PayLoad data;
}
public class PayLoad
{
public string key;
}
you can create the request as below
GCMRequest req = new GCMRequest();
List<string> tokens = new List<string>();
// .. fill the tokens to the 'tokens' list
req.registration_ids = tokens;
req.data.key = "Hi, how are you"; // message you want to send
string json = new JavaScriptSerializer().Serialize(req);
Hope this will help.
Related
Dears,
I am querying Spotify API using the following code
public Spotify_Search_Result Search(string artist_name, string song_name, int limit=1) {
Spotify_Search_Result result = new Spotify_Search_Result();
string text = artist_name + "%20" + song_name;
//string text = artist_name + "+" + song_name;
//string text = artist_name + " " + song_name;
//string text = Uri.EscapeDataString(artist_name) + " " + Uri.EscapeDataString(song_name);
//string text = Uri.EscapeDataString(artist_name) + "%20" + Uri.EscapeDataString(song_name);
//string text = Uri.EscapeDataString(artist_name) + "+" + Uri.EscapeDataString(song_name);
string url = "https://api.spotify.com/v1/search";
string query = url +
"?q="+
text+
"&type=track"+
"&offset=0"+
"&limit="+
limit.ToString();
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(query);
webRequest.Method = "GET";
webRequest.ContentType = "application/json";
webRequest.Accept = "application/json";
webRequest.Headers.Add("Authorization", "Bearer " + access_token);
String json = null;
try
{
HttpWebResponse resp = (HttpWebResponse)webRequest.GetResponse();
using (Stream respStr = resp.GetResponseStream())
{
using (StreamReader rdr = new StreamReader(respStr, Encoding.UTF8))
{
//should get back a string i can then turn to json and parse for accesstoken
json = rdr.ReadToEnd();
rdr.Close();
}
}
}
catch (Exception ex) {
Console.WriteLine("Spotify search result error: " + ex.Message + " ["+artist_name+"]-["+song_name+"]" );
}
if (json != null)
{
result = JsonConvert.DeserializeObject<Spotify_Search_Result>(json);
}
return result;
}
Problem: for certain values of artist_name and song_name this code returns no matching items.
Example: artist_name=Delta V
song_name=Il primo giorno del mondo
variable json value will be:
{
"tracks" : {
"href" : "https://api.spotify.com/v1/search?query=Delta+V+Il+Primo+Giorno+Del+Mondo&type=track&offset=0&limit=20",
"items" : [ ],
"limit" : 20,
"next" : null,
"offset" : 0,
"previous" : null,
"total" : 0
}
}
if I type same artist_name and song_name in SpotifyForDevelopers console I get a good match.
Now...where is the problem? I think it is the way I format the "text" and pass it to the API. I am not sure.
As you see from code I have tried different ways of formatting "text" variable.
Any hint on what I am doing wrong?
Thanks!
I think your code is correct and the problem could lie with the "market" parameter, i.e. songs can be available for some countries and unavailable for others.
Your example query will return the right result if you set the market to Italy (IT) but not when set to United States (US), for example (notice the added market=IT):
https://api.spotify.com/v1/search?query=elta%20V%20Il%20primo%20giorno%20del%20mondo&type=track&offset=0&limit=20&market=IT
Maybe setting the market correctly might help to reduce/avoid the issue.
I am working on a program which creates multiple change stream, so I am working on doing the same in single stream rather than creating multiple watches,
my sessionValues contains multiple ids,
string[] sessionValues = list.ToArray();
filter = "{ $and: [ { operationType: 'insert' }, " + "{ 'fullDocument.appId' : {$in:['" + sessionValues + "']}} ] }";
var pipeline = new EmptyPipelineDefinition<ChangeStreamDocument<BsonDocument>>().Match(filter);
// var changeStream = Collection.Watch(pipeline, options).ToEnumerable().GetEnumerator();
DBObjects.DB.WriteLog(DBObjects.LogLevel.Info, "Log data change stream is now configured");
var cursor = Collection.Watch(pipeline, options);
flag = true;
var enumerator = cursor.ToEnumerable().GetEnumerator();
I want to use $in to find in my sessionValues variable rather than defining values in conventional [] way, coz I wont be able to define as I am adding values in my array. and want $in to find in array.
Because my format was bson, i managed to do it with the following,
string sessionValues = "";
foreach (var item in array)
{
sessionValues += "'" + item + "',";
}
filter = "{ $and: [ { operationType: 'insert' }, " + "{ 'fullDocument.appId' : {$in:[" + sessionValues + "]}} ] }";
the above method worked perfectly fine for me, the values in the list were fetching properly.
I have a List class List<Data> dataValue = new List<Data> where Data contains List of destination's(multiple) and List of source's(multiple) details. I want to loop through and assign each of the destination and source to the List below. I am finally converting all the data to a JSON file.
foreach (var data in dataValue)
{
var value = new RuleJsonclassTemplate
{
type = data.type,
mapping = new List<Mapping>() { new Mapping() { value = data.destination, key = data.source } },
description = data.description,
title = data.title
}
}
string JSONresult = JsonConvert.SerializeObject(value);
string path = outputdir + Outputfilename;
using (var writer = new StreamWriter(path, true))
{
writer.WriteLine(JSONresult.ToString());
writer.Close();
}
class Mapping
{
public string destination { get; set; }
public string source { get; set; }
}
The JSON output should look like below,
{
"type": "Type1",
"mapping": [
{
"value": "destination1",
"key": "source1"
},
{
"value": "destination2",
"key": "source1"
},
{
"value": "destination3",
"key": "source3"
}
],
"description": "Test description",
"title": "Test title"
}
Can you please suggest on how can I achieve this? For reference my sample code at https://dotnetfiddle.net/W49buW
It would be :
public string ConvertToJSON(List<string>SourceStr,List<string>DestinationStr)
{
string json = "{" + Environment.NewLine + "mapping : [" + Environment.NewLine;
for (int i = 0; i < SourceStr.Count; i++)
{
json = json + "{" + Environment.NewLine + "value : " + SourceStr[i].ToString() + ","+ Environment.NewLine
+ "key : " + DestinationStr[i].ToString() + Environment.NewLine + "}," + Environment.NewLine;
}
json = json.Substring(0, json.LastIndexOf(','));
json = json + "]" + Environment.NewLine + "}";
return json;
}
I was able to fix the problem by adding another method which add's the data 1 by 1 to the list. Updated my sample code at https://dotnetfiddle.net/W49buW. Hope this helps for folks looking for the solution.
I'm having an issue while trying to read a json in unity. I get this message "ArgumentException: JSON parse error: Invalid value.". My JSON looks like:
[{"equipo":"Boca","pj":"5","pg":"3","pp":"2"}] and it is ok in unity.
Here is my info class
[Serializable]
public class Response
{
public string equipo;
public int pj;
public int pg;
public int pp;
}
And here is the coroutine that I call in the awake function
IEnumerator RequestCorutine()
{
var req = new WWW("http://localhost/test/item.php?team=Boca");
yield return req;
print(req.text);
//var json = req.text;
string json = System.Text.Encoding.UTF8.GetString(req.bytes, 3,
req.bytes.Length - 3);
Response response = JsonUtility.FromJson<Response>(json);
print("Equipo: " + response.equipo + " PJ: " + response.pj + " PG: " +
response.pg + " PP: " + response.pp);
}
I get the error in this line: Response response = JsonUtility.FromJson<Response>(json);
I apologize for my English, is not that good. Thanks.
[{"equipo":"Boca","pj":"5","pg":"3","pp":"2"}]
should be
{"equipo":"Boca","pj":5,"pg":3,"pp":2}
because square brackets are used to declare arrays in json. You were declaring a List<Response> instead of a single Response. Also, I removed the quotes around the numbers.
Below is my code,
List<string> modified_listofstrings = new List<string>();
string sJSON = "";
System.Web.Script.Serialization.JavaScriptSerializer jSearializer =
new System.Web.Script.Serialization.JavaScriptSerializer();
resulted_value = final_resulted_series_name + ":" + period_name + ":" + period_final_value;
modified_listofstrings.Add(resulted_value);
json_resultedvalue = JsonConvert.SerializeObject(resulted_value);
modified_listofstrings.Add(json_resultedvalue);
sJSON = jSearializer.Serialize(modified_listofstrings);
return sJSON;
But on following line ,
sJSON = jSearializer.Serialize(modified_listofstrings);
I am getting an error as Cannot implicitly convert type string to system.collection.generic.list
Let me fix your approach - instead of building JSON strings using your data, and then putting them into a list and trying again to serialize that, what you should do is build your data structure and then serialize it in one go.
Since I couldn't figure out the structure of the data in your post, here is an example with a different format:
public struct Person
{
public string Name;
public int Age;
public List<string> FavoriteBands;
}
The easiest way to serialize it is to use Newtonsoft JSON. If you have an object called person, then you would serialize it using
string json = JsonConvert.SerializeObject(person);
Now suppose you have a list of these objects i.e. List<Person> people = GetTheListFromSomewhere();, then you would serialize it using
string json = Newtonsoft.Json.JsonConvert.SerializeObject(people);
Go ahead and try it!
resulted_value = final_resulted_series_name + ":" + period_name + ":" + period_final_value;
This is not a valid JSON. It must have key, value format separated by comma. I guess it should be:
resulted_value = "{series_name : \"" + final_resulted_series_name + "\",period_name: \"" + period_name + "\",period_final_value: \"" + period_final_value + "\"}";
so the result should be something like this:
{series_name: "whatever_series_name_is", period_name:
"whatever_period_name_is",period_final_value:
"whatever_period_final_value_is"}