i am trying to detect what language the written txt of player.LastChat is, and i am having some difficulties.
Here's the code i have:
String[] words = player.LastChat.Trim().Split(new Char[]{' ','\t',',','.',':','!','?',';','(',')',']','[','"'});
StringBuilder edited = new StringBuilder();
// Remove exception list words from line
foreach (String w in words) {
if (plugin.isInList(w, "good_words")) {
continue;
}
edited.Append(w);
edited.Append(" ");
}
// URL Encode edited string
String UnreservedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~";
StringBuilder Result = new StringBuilder();
String Input = edited.ToString();
for (int x = 0; x < Input.Length; ++x)
{
if (UnreservedChars.IndexOf(Input[x]) != -1)
Result.Append(Input[x]);
else
Result.Append("%").Append(String.Format("{0:X2}", (int)Input[x]));
}
String key = "API KEY";
// Test for badness
bool jsonresult = false;
try {
WebClient client = new WebClient();
String json = client.DownloadString("https://www.googleapis.com/language/translate/v2/detect?key=" + key + "&q=" + Result.ToString());
jsonresult = json.Contains("en");
} catch (Exception e) {
plugin.ConsoleWrite("Language check failed! Error: " + e);
}
if (!jsonresult) {
return true;
}
plugin.ConsoleWrite("Language: " + jsonresult);
return jsonresult; // for Actions
So, what i am trying to achieve, is to return true if it is any other language than "en" (english), but it is returning true no matter what.
The response from google is this:
{
"data": {
"detections": [
[
{
"language": "en",
"isReliable": false,
"confidence": 0.03396887
}
]
]
}
}
Any help is much appreciated, and i have no idea how to code, this code is borrowed from another script.
Regards.
To make method work as described, you should change:
if (!jsonresult) {
return true;
}
plugin.ConsoleWrite("Language: " + jsonresult);
return jsonresult;
to:
plugin.ConsoleWrite("Language: " + jsonresult);
return !jsonresult;
also this line
jsonresult = json.Contains("en");
is checking for any occurance of "en" in json text (and is found in "confidence" in your json). What you should do, is to parse Json using json.net (or other lib), or simply do this (but is an ugly hack):
jsonresult = json.Contains("\"language\": \"en\",");
Related
I'm trying to get covid-19 results (only information about Iran) from an Api and show it on a textbox.
and the full result (all countries) that i get from the Api is a json format.
so to get only Iran section i made a Function that loops through lines of the string one by one and check if in that line there is a "{" and if yes get index of that and continue checking if in another line there is a "}" and get index of that too then check if between these, there is "Iran" then add this text (from "{" to "}") in a string:
private string getBetween(string strSourceText, string strStartingPosition, string strEndingPosition)
{
int Starting_CurlyBracket_Index = 0;
int Ending_CurlyBracket_Index = 0;
string FinalText = null;
bool isTurnTo_firstIf = true;
foreach (var line in strSourceText.Split('\r', '\n'))
{
if (isTurnTo_firstIf == true)
{
if (line.Contains(strStartingPosition))
{
Starting_CurlyBracket_Index = line.IndexOf(strStartingPosition); //i think problem is here
isTurnTo_firstIf = false;
}
}
else if (isTurnTo_firstIf == false)
{
if (line.Contains(strEndingPosition))
{
Ending_CurlyBracket_Index = line.IndexOf(strEndingPosition); //i think problem is here
if (strSourceText.Substring(Starting_CurlyBracket_Index, Ending_CurlyBracket_Index - Starting_CurlyBracket_Index).Contains("Iran")) //error here
{
FinalText = strSourceText.Substring(Starting_CurlyBracket_Index, Ending_CurlyBracket_Index - Starting_CurlyBracket_Index);
break;
}
else
{
isTurnTo_firstIf = true;
}
}
}
}
return FinalText;
}
and i call the function like this:
string OnlyIranSection = getBetween(Sorted_Covid19_Result, "{", "}"); //Sorted_Covid19_Result is the full result in json format that converted to string
textBox1.Text = OnlyIranSection;
but i get this Error:
and i know.. its because it gets indexes in the current line but what i need is getting that index in the strSourceText so i can show only this section of the whole result:
USING JSON
As per the comments I read it was really needed to use JSON utility to achieve your needs easier.
You can start with this basic example:
static void Main(string[] args)
{
string jsonString = #"{
""results"": [
{""continent"":""Asia"",""country"":""Indonesia""},
{""continent"":""Asia"",""country"":""Iran""},
{""continent"":""Asia"",""country"":""Philippines""}
]
}";
var result = JsonConvert.DeserializeObject<JsonResult>(jsonString);
var iranInfo = result.InfoList.Where(i => i.Country.ToString() == "Iran").FirstOrDefault();
}
public class JsonResult
{
[JsonProperty("results")]
public List<Info> InfoList { get; set; }
}
public class Info
{
public object Continent { get; set; }
public object Country { get; set; }
}
UPDATE: USING INDEX
As long as the structure of the JSON is consistent always then this kind of sample solution can give you hint.
Console.WriteLine("Original JSON:");
Console.WriteLine(jsonString);
Console.WriteLine();
Console.WriteLine("Step1: Make the json as single line,");
jsonString = jsonString.Replace(" ", "").Replace(Environment.NewLine, " ");
Console.WriteLine(jsonString);
Console.WriteLine();
Console.WriteLine("Step2: Get index of country Iran. And use that index to get the below output using substring.");
var iranIndex = jsonString.ToLower().IndexOf(#"""country"":""iran""");
var iranInitialInfo = jsonString.Substring(iranIndex);
Console.WriteLine(iranInitialInfo);
Console.WriteLine();
Console.WriteLine("Step3: Get inedx of continent. And use that index to get below output using substring.");
var continentIndex = iranInitialInfo.IndexOf(#"""continent"":");
iranInitialInfo = iranInitialInfo.Substring(0, continentIndex-3);
Console.WriteLine(iranInitialInfo);
Console.WriteLine();
Console.WriteLine("Step4: Get the first part of the info by using. And combine it with the initialInfo to bring the output below.");
var beginningIranInfo = jsonString.Substring(0, iranIndex);
var lastOpenCurlyBraceIndex = beginningIranInfo.LastIndexOf("{");
beginningIranInfo = beginningIranInfo.Substring(lastOpenCurlyBraceIndex);
var iranInfo = beginningIranInfo + iranInitialInfo;
Console.WriteLine(iranInfo);
OUTPUT USING INDEX:
This case should be very simple, but I have a little bug that I don't know how to solve. I'm working with a Xamarin.Forms app that does some API calls to a localhost API running in my PC. This is the main part of the API call:
try
{
HttpClient client = new HttpClient();
client.MaxResponseContentBufferSize = BUFFER_SIZE;
client.DefaultRequestHeaders.Add(CULTURE_ID, "es");
client.DefaultRequestHeaders.Add(VALUE, LAST_WEEK_VALUE);
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(BEARER, token);
var content = new StringContent("", System.Text.Encoding.UTF8, APPLICATION_JSON);
HttpResponseMessage response = await client.GetAsync(url);
var result = await response.Content.ReadAsStringAsync();
List<SubProductParser> prices;
try
{
prices = JsonConvert.DeserializeObject<List<SubProductParser>>(result);
}
catch
{
// exception missin the final character in JSON "]"
}
return prices.ElementAt(0);
}
catch
{
return null;
}
The content of the result variable before trying to do the deserialize:
As you can see is not a valid JSON format, is strange because as you can see in the next screenshot when I do the same API call with POSTMAN is working always perfectly, but I don't know why sometimes doesn't receive all the JSON content when I do the call in the app.
Any idea, seeing the variable result content in debug, sometimes doesn't have the final character of the JSON "]", the API call is made after a button tapped in this way:
private async void Handle_Item_Tapped(object sender, ItemTappedEventArgs e)
{
var selected = e.Item as ProductParser;
var lastPrice= await ApiConnector.GetLastWeekSubProductPrices(
App.ViewModel.LoginViewModel.SesionToken,
subCatViewModel.Selected.ProductId,
subCatViewModel.Selected.Id);
await subCatViewModel.IsFavorite();
subCatViewModel.BarViewModel.Selected = selected;
subCatViewModel.BarViewModel.Categories = _categories;
subCatViewModel.LinearViewModel.Selected = selected;
subCatViewModel.LinearViewModel.Categories = _categories;
await Navigation.PushAsync(new Graphs(subCatViewModel));
}
The API functions that implement this API call, the API is developed in Larvael using php. I tried to simplify them as much as possible:
public static function getLastWeekPrices($cultureId)
{
self::initialize();
$year = self::getLastYear();
$prejson = json_encode(DB::table('product')
->join(SOME_CONDITIONS..)
...
->where(SOME_CONDITIONS..)
...
->select(SOME_ROWS)
->get());
$currentWeek = self::getCurrentWeek();
$json_decoded = json_decode($prejson, true);
$json_final = array();
foreach ($json_decoded as $slider_value)
{
$max_week= DB::table(SOME_CONDITIONS)
->max(SOME_CONDITIONS);
$last_week_price = json_encode(SOME_CONDITIONS)
...
->get());
...
//ADDING SOME VALUES TO $slider_value
...
array_push($json_final, $slider_value);
}
return json_encode($json_final);
}
public static function subProductsPricesQuery($id, $subId, $cultureId, $values)
{
self::initialize();
if (self::doesCultureExist($cultureId)){
if ($values == self::LAST_WEEK) {
$json = self::getLastWeekSubProductPrices($id, $subId, $cultureId);
}
....
}
}
public function FunctionCalledInAPIRoute(Request $request, $id, $subId)
{
try{
$user = JWTAuth::parseToken()->toUser();
$json = DatabaseQuerys::subProductsPricesQuery($id, $subId, $request->header("cultureId"), $request->header("value"));
return self::jsonIsEmpty($json);
}catch(JWTException $e){
return $this->respondInternalError("Any token found!");
}
}
public static function jsonIsEmpty($products)
{
self::initialize();
$initial = $products[0] === "[" ? TRUE : FALSE;
$final = $products[1] === "]" ? TRUE : FALSE ;
if (strlen($products) === 0 || ($initial == TRUE && $final == TRUE))
{
header('Content-type:application/json;charset=utf-8');
return (new self)->respondNotFound("Any result found in this category");
} else {
header('Content-type:application/json;charset=utf-8');
return $products;
}
}
The JsonIsEmpty is a little method that I create to control if the database return something, if not as the functions return json_encoder($array), always will be [].
The content of the variable result when receives the faulty JSON:
[
{
"id": 19,
"name": "Conejo de más de 2125 gr",
"units": "€/Kg",
"price": "1.91",
"week": 10,
"year": 2019,
"last_price": "1.79",
"difference": "0.12",
"arrow": "up_arrow.png"
}
As you can see is missing the closing "]".
I implemented a little test to see if the app is working fine, the test function and the function that calls it:
public static function jsonIsEmptyTest($products)
{
self::initialize();
$initial = $products[0] === "[" ? TRUE : FALSE;
$final = $products[1] === "]" ? TRUE : FALSE ;
if (strlen($products) === 0 || ($initial == FALSE && $final == FALSE))
{
return 1;
} else {
return 0;
}
}
public static function the foo(....)
{
$correct = 0;
$wrong = 0;
for($x = 0; $x < 1000; $x++)
{
$json = DatabaseQuerys::subProductsPricesQuery($id, $subId, $request->header("cultureId"), $request->header("value"));
print_r($json);
print_r("\n\n");
$result = JsonController::jsonIsEmptyTest($json);
if($result == 0)
{
$correct = $correct + 1;
}
if($result == 1)
{
$wrong = $wrong + 1;
}
}
print_r("Correct: ");
print_r($correct);
print_r("\n");
print_r("Wrong: ");
print_r($wrong);
exit();
}
Doing the API call with postman the result is:
I'm Getting this error when accessing data from a json file.
I'm trying to follow the following tutorial: http://wiki.unity3d.com/index.php/SimpleJSON
and created a test.json file, that I want to extract data from containing:
{
"version": "1.0",
"data": {
"sampleArray": [
"string value",
5,
{
"name": "sub object"
}
]
}
}
using the following code in Unity:
void LoadFiles()
{
FileInfo f = m_info[0]; //Array of Files in Folder
// I had a foreach loop here, but wanted to specify the file for testing before I tried to parse through one of my own
print("I Found : " + f);
var N = JSONNode.LoadFromFile(f.FullName);
var versionString = N["version"].Value; // versionString will be a string containing "1.0"
var versionNumber = N["version"].AsFloat; // versionNumber will be a float containing 1.0
var name = N["data"]["sampleArray"][2]["name"];// name will be a string containing "sub object"
print("vs=" + versionString + " vn=" + versionNumber + " name=" + name);
}
and all i get is Unknown tags, from what I gather from the source :
public static JSONNode Deserialize(System.IO.BinaryReader aReader)
{
JSONBinaryTag type = (JSONBinaryTag)aReader.ReadByte();
switch(type)
{
case JSONBinaryTag.Array:
{
int count = aReader.ReadInt32();
JSONArray tmp = new JSONArray();
for(int i = 0; i < count; i++)
tmp.Add(Deserialize(aReader));
return tmp;
}
case JSONBinaryTag.Class:
{
int count = aReader.ReadInt32();
JSONClass tmp = new JSONClass();
for(int i = 0; i < count; i++)
{
string key = aReader.ReadString();
var val = Deserialize(aReader);
tmp.Add(key, val);
}
return tmp;
}
case JSONBinaryTag.Value:
{
return new JSONData(aReader.ReadString());
}
case JSONBinaryTag.IntValue:
{
return new JSONData(aReader.ReadInt32());
}
case JSONBinaryTag.DoubleValue:
{
return new JSONData(aReader.ReadDouble());
}
case JSONBinaryTag.BoolValue:
{
return new JSONData(aReader.ReadBoolean());
}
case JSONBinaryTag.FloatValue:
{
return new JSONData(aReader.ReadSingle());
}
default:
{
throw new Exception("Error deserializing JSON. Unknown tag: " + type);
}
}
}
I'm falling all the way through the Switch, but with .Value or .AsFloat I should hit those case statements. Any Idea what's going on, is this code to old for Unity 5.0 ?
It seems like I was under false pretenses, that the JSON file was like XML, text, well it seems it is not, or at least assumed to be binary by SimpleJson when reading files. I tried writing the "Text" to a file, and then reading it and it worked fine. So this is an error where I assumed the data in the examples to be text.
JSONNode.LoadFromFile function instead to JSONNode.Parse(string) convert stream to string
System.IO.FileStream fs = System.IO.File.OpenRead(f.FullName);
long length = fs.Length;
byte[] stream = new byte[length];
fs.Read(stream, 0, (int)length);
string json = System.Text.Encoding.UTF8.GetString(stream);
var N = JSONNode.Parse(json);
I'm trying to write lines in a valid JSON format using C# in a efficient way
What the file should look like:
[
{
"uuid": "c92161ba-7571-3313-9b59-5c615d25251c",
"name": "thijmen321"
},
{
"uuid": "3b90891d-e6fc-44cc-a1a8-e822378ec148",
"name": "TehGTypo"
},
{
"uuid": "5f820c39-5883-4392-b174-3125ac05e38c",
"name": "CaptainSparklez"
}
]
I already have the names and the UUIDs, but I need a way to write them to a file. I want to do this one by one, so, first the file looks like this:
[
{
"uuid": "c92161ba-7571-3313-9b59-5c615d25251c",
"name": "thijmen321"
}
]
Then like this:
[
{
"uuid": "c92161ba-7571-3313-9b59-5c615d25251c",
"name": "thijmen321"
},
{
"uuid": "3b90891d-e6fc-44cc-a1a8-e822378ec148",
"name": "TehGTypo"
}
]
etc. But of course, the UUIDs and the names are different, so how can I do this in a efficient way without using any APIs etc.?
My current (really inefficient) code:
public void addToWhitelist()
{
if (String.IsNullOrEmpty(whitelistAddTextBox.Text)) return;
string player = String.Empty;
try
{
string url = String.Format("https://api.mojang.com/users/profiles/minecraft/{0}", whitelistAddTextBox.Text);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(url));
request.Credentials = CredentialCache.DefaultCredentials;
using (WebResponse response = request.GetResponse())
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
player = reader.ReadToEnd();
}
catch (WebException ex)
{
Extensions.ShowError("Cannot connect to http://api.mojang.com/! Check if you have a valid internet connection. Stacktrace: " + ex, MessageBoxIcon.Error);
}
catch (Exception ex)
{
Extensions.ShowError("An error occured! Stacktrace: " + ex, MessageBoxIcon.Error);
}
if (String.IsNullOrWhiteSpace(player)) { Extensions.ShowError("This player doesn't seem to exist.", MessageBoxIcon.Error); return; }
player = player.Replace(",\"legacy\":true", "")
.Replace("\"id", " \"uuid")
.Replace("\"name", " \"name")
.Replace(",", ",\n")
.Replace("{", " {\n")
.Replace("}", "\n },");
File.WriteAllText(Program.programPath + #"\Servers\" + servers[currentIndex].Name + #"\whitelist.json", "");
try
{
using (StreamWriter sw = File.AppendText(Program.programPath + #"\Servers\" + servers[currentIndex].Name + #"\whitelist.json"))
{
sw.WriteLine("[");
foreach (string s in File.ReadAllLines(Program.programPath + #"\Servers\" + servers[currentIndex].Name + #"\whitelist.json"))
if (s.Contains("[") || s.Contains("]") || s.Equals(Environment.NewLine)) continue;
else sw.WriteLine(s);
sw.WriteLine(player);
sw.WriteLine("]");
whitelistListBox.Items.Add("\n" + whitelistAddTextBox.Text);
}
}
catch (Exception ex) { Extensions.ShowError("An error occured while update whitelist.json! Stacktrace: " + ex); }
whitelistAddTextBox.Clear();
}
The recommand "Microsoft" way is with a data contract and the DataContractJsonSerializer.. see here
https://msdn.microsoft.com/de-de/library/system.runtime.serialization.json.datacontractjsonserializer%28v=vs.110%29.aspx
an example of the contact would be:
[DataContract]
internal class Person
{
[DataMember]
internal string name;
[DataMember]
internal string Uuid ;
}
you use the class in the following way (obviously)
Person p = new Person();
p.name = "John";
p.Uuid = "3b90891d-e6fc-44cc-a1a8-e822378ec148";
and serialize it with the Contract Serializer
MemoryStream stream1 = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Person));
ser.WriteObject(stream1, p);
example to show the serialzed data:
stream1.Position = 0;
StreamReader sr = new StreamReader(stream1);
Console.WriteLine(sr.ReadToEnd());
Try json.net it will do the serialization job for you: http://www.newtonsoft.com/json
I would use a JSON Serializer like http://www.newtonsoft.com/json
This would allow you to roll your uuid/name as a class, instead of doing the parsing yourself
So something like:
internal class UuidNamePair
{
string Uuid { get; set; }
string Name { get; set; }
}
Then when calling this, you would just do something like this:
List<UuidNamePair> lst = new List<UuidNamePair>();
lst.Add(new UuidNamePair() { Name = "thijmen321", Uuid = "c92161ba-7571-3313-9b59-5c615d25251c" });
lst.Add(new UuidNamePair() { Name = "TehGTypo", Uuid = "3b90891d-e6fc-44cc-a1a8-e822378ec148" });
string json = JsonConvert.SerializeObject(lst, Formatting.Indented);
Console.WriteLine(json);
Instead of the Console.WriteLine, you could do your POST to a web service or however you're trying to use this json.
Here is a sample of my code.
Here I recieve a string variable from another page.
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
string newparameter = this.NavigationContext.QueryString["search"];
weareusingxml();
displayResults(newparameter);
}
private void displayResults(string search)
{
bool flag = false;
try
{
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream stream = myIsolatedStorage.OpenFile("People.xml", FileMode.Open))
{
XmlSerializer serializer = new XmlSerializer(typeof(List<Person>));
List<Person> data = (List<Person>)serializer.Deserialize(stream);
List<Result> results = new List<Result>();
for (int i = 0; i < data.Count; i++)
{
string temp1 = data[i].name.ToUpper();
string temp2 = "*" + search.ToUpper() + "*";
if (temp1 == temp2)
{
results.Add(new Result() {name = data[i].name, gender = data[i].gender, pronouciation = data[i].pronouciation, definition = data[i].definition, audio = data[i].audio });
flag = true;
}
}
this.listBox.ItemsSource = results;
}
catch
{
textBlock1.Text = "error loading page";
}
if(!flag)
{
textBlock1.Text = "no matching results";
}
}
Nothing is loaded into the list when the code is run, I just get the message "no matching results".
Looks like you are trying to do a contains search (my guess based on your addition of the * around the search string. You can remove the '*' and do a string.Contains match.
Try this.
string temp1 = data[i].name.ToUpper();
string temp2 = search.ToUpper()
if (temp1.Contains(temp2))
{
It looks like you are trying to check if one string contains another (ie substring match) and not if they are equal.
In C#, you do this like this:
haystack = "Applejuice box";
needle = "juice";
if (haystack.Contains(needle))
{
// Match
}
Or, in your case (and skip the * you added to the string temp2)
if (temp1.Contains(temp2))
{
// add them to the list
}
Have you checked to make sure data.Count > 0?