Invalid JSON error when I add non ASCII characters to Twitter API v2 rules

Viewed 23

I use the Java class that Twitter provides in its GitHub for the filtered stream endpoint (https://github.com/twitterdev/Twitter-API-v2-sample-code/blob/main/Filtered-Stream/FilteredStreamDemo.java) and it works fine.

However, when I add in a rule a word that contains non ASCII characters (for example the word "siccità") it returns the error:

{"errors":[{"parameters":{},"message":"Invalid JSON"}],"title":"Invalid Request","detail":"One or more parameters to your request was invalid.","type":"https://api.twitter.com/2/problems/invalid-request"}

I tried to convert the word to UTF-8 but it did not work at all. Is there any way to add words with non ASCII characters to the Twitter API v2 rules in Java?

1 Answers

In the class FilteredStreamDemo.java that Twitter provides here: https://github.com/twitterdev/Twitter-API-v2-sample-code/blob/main/Filtered-Stream/FilteredStreamDemo.java you have to go to the class createRules and replace this line of code:

StringEntity body = new StringEntity(getFormattedString("{\"add\": [%s]}", rules));

with that:

StringEntity body = new StringEntity(getFormattedString("{\"add\": [%s]}", rules), "UTF-8");

and it will work fine even when there are non ASCII characters in the rules.

Related