When I get http response it looks like this:
{
"course_editions": {
"2014/SL": [
{
"course_id": "06-DEGZLI0",
"term_id": "2014/SL",
"course_name": {
"en": "Preparation for bachelor exam",
}
},
{
"course_id": "06-DPRALW0",
"term_id": "2014/SL",
"course_name": {
"en": "Work experience",
}
},
{
I would like to be able to extract course title only, f.e.:
Work experience
Preparation for bachelor exam
I've tried this:
string probably_json = GetResponse(url_courses);
object obj = JsonConvert.DeserializeObject(probably_json);
using (StringReader reader = new StringReader(obj.ToString().Replace("\\t", " ").Replace("\\n", "\n")))
{
string line;
int lineNo = 0;
while ((line = reader.ReadLine()) != null)
{
if (line.Contains("en"))
{
string output = line.Substring(0, line.Length-1);
Console.WriteLine(output);
}
++lineNo;
}
} // End Using StreamReader
But that's all I've got:
"en": "Preparation for bachelor exam" "en": "Work experience"
what am I supposed to do, to get course title only ?
If you are using json.net anyways, make it do some work, don't parse yourself:
var result = JObject
.Parse(probably_json)
.SelectTokens("['course_editions'].['2014/SL'].[*].['course_name'].['en']");
Related
I am trying to search a json file with a string and then return a value from the same object as that string. This is a part of the json file:
[
"7c6b2f",
"EYZ",
"Australia",
1611990353,
1611990419,
144.8364,
-37.6611,
13114.02,
false,
50.42,
171.56,
null,
null,
null,
"5064",
true,
0
],
[
"7c6b0c",
"JST",
"New-Zealand",
1611990440,
1611990440,
148.4636,
-33.7973,
10668,
false,
248.2,
37.84,
-0.33,
null,
11170.92,
"1461",
false,
0
]
I want to have it so that if the user enters EYZ then the code will return Australia. I am currently setting the json file to a string but I am not sure how you would create objects to search in this scenario.
First of all, this is not a valid json file. You need to enclose it in an array element:
[
[
"xyz"
...
],
[
]
]
Once your object is valid, you can you the JSON.Net library to parse it in your code
// Here you'll have your value
string json = #"[
'Small',
'Medium',
'Large'
]";
JArray a = JArray.Parse(json);
And you can see How to access elements of a JArray (or iterate over them) how to iterate/access them.
JSON.Net
public static string Search(string input)
{
using (var sr = new StreamReader("your.json"))
{
var reader = new JsonTextReader(sr);
while (reader.Read())
{
if (reader.TokenType==JsonToken.String)
{
var value = reader.ReadAsString();
if (value == input)
{
return reader.ReadAsString();
}
}
}
}
return null;
}
SystemExtensions.Core
public static string Search(string input)
{
using (var sr = new StreamReader("your.json"))
{
var reader = JsonReader.CreateJson5(sr, 2048);
while (reader.Read())
{
if (reader.IsString)
{
var value = reader.GetString();
if (value == input)
{
if (reader.Read() && reader.IsString)
{
return reader.GetString();
}
}
}
}
}
return null;
}
im trying to get a value of JSON with the substring from a config,
using (WebClient wc = new WebClient())
{
string json = wc.DownloadString("****");
dynamic dobj = JsonConvert.DeserializeObject<dynamic>(json);
string kek = dobj[0].ServerSystem.isActive;
if(kek == "True")
{
Console.WriteLine(kek);
Console.ReadLine();
}
else
{
Console.WriteLine(kek);
Console.ReadLine();
}
}
JSON:
[
{
"ServerSystem": {
"isActive": "True",
"Time": "120S"
}
},
{
"License1": {
"Description": "Lorem ipsum dolor gg amet",
"Value": "1"
}
}
]
But i want to get the Value ServerSystem.[FROMCONFIG], but i dont know how to insert it, so i know how to read from a config, but i cant just dO: string kek = dobj[0].ServerSystem + ".BLALBALA";
So how to do it?
Actually your pseudocode nearly got it right.
var keytoget = "Time";
string value dobj[0].ServerSystem[keytoget]
I know it sounds basic but all answers around this question have been stupidly large and bulky code that does not allow the functionality i need. i need to parse this json array.
[
{
"label":"Cow (1)",
"value":3309
},
{
"label":"Cow (1)",
"value":14998
},
{
"label":"Cow (4)",
"value":20969
},
{
"label":"Cow (4)",
"value":20970
},
{
"label":"Cow (4)",
"value":20971
},
{
"label":"Cowardly Bandit",
"value":1886
},
{
"label":"Cow calf (1)",
"value":2310
},
{
"label":"Coward in armour (82)",
"value":5097
},
{
"label":"Coward with bow (105)",
"value":6049
},
{
"label":"Cow calf (1)",
"value":20979
},
{
"label":"Undead cow (4)",
"value":1691
},
{
"label":"Plague cow",
"value":1998
},
{
"label":"Plague cow",
"value":1999
},
{
"label":"Unicow (57)",
"value":5603
},
{
"label":"Zombie cow (1)",
"value":18597
},
{
"label":"Zombie cow (1)",
"value":20928
},
{
"label":"Super Cow (5)",
"value":21497
},
{
"label":"Dairy cow",
"value":22418
},
{
"label":"Armoured cow thing (62)",
"value":5986
},
{
"label":"Armoured cow thing (62)",
"value":6048
}
]
And when i try to access the data point inside the array it returns null, code:
Stream stream = client.OpenRead("http://services.runescape.com/m=itemdb_rs/bestiary/beastSearch.json?term=" + Input);
StreamReader reader = new StreamReader(stream);
jObject = JObject.Parse(reader.ReadToEnd());
stream.Close();
//put items into list view
// i is the number where the json object is in the array
var lvi = new ListViewItem(new string[] { (string)jObject[i]["label"], (string)jObject[i]["value"] });
I do not want to use classes
Found error in your code. Instead:
JObject.Parse(reader.ReadToEnd());
Write (JObject -> JArray):
string text = reader.ReadToEnd();
var jObject = JArray.Parse(text);
Also when write operation in 2 lines, you will see where the error: in reading from the stream or in serialization.
Not wanting to use classes is weird but not impossible.
var json = reader.ReadToEnd();
var objects = JsonConvert.DeserializeObject<dynamic[]>(json);
var lvi = new ListViewItem(new string[] { (string)objects[i].label, (string)objects[i].value });
Try my answer to this question :
public IEnumerable<MeItem> DeserializeListFromJson(string jsonArray)
{
return JsonConverter.DeserializeObject<List<JObject>>(jsonArray).Select( obj => DeserializeFromJson(obj) );
}
public MeItem DeserializeFromJson(string jsonString)
{
return JsonConvert.DeserializeObject<MeItem>(jsonString);
}
You can find necessary detailed informations in my answer for this question and this one
Edit:
If you do not want to use classes then you can just modify DeserializeFromJson() method into something like this :
public KeyValuePair<string, string> DeserializeFromJson(JObject obj)
{
return new KeyValuePair<string, string>(obj.SelectToken("label").Value<string>(), obj.SelectToken("value").Value<string>());
}
Which will require to modify DeserializeListFromJson() method into :
public IEnumerable<KeyValuePair<string,string>> DeserializeListFromJson(string jsonArray)
{
return JsonConverter.DeserializeObject<List<JObject>>(jsonArray).Select( obj => DeserializeFromJson(obj) );
}
Usage with your case :
Stream stream = client.OpenRead("http://services.runescape.com/m=itemdb_rs/bestiary/beastSearch.json?term=" + Input);
ListViewItem item = null;
using (StreamReader reader = new StreamReader(stream))
{
KeyValuePair<string, string> selected = DeserializeListFromJson(reader.ReadToEnd()).ElementAt(i);
item = new ListViewItem(new string[] { selected.Key, selected.Value });
}
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.
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\",");